Calculating the height of a triangle can be done using different methods depending on the given information. In this example, I will cover two methods: using the area and base of the triangle, and using Heron’s formula for triangles where the side lengths are known.
Method 1: Using Area and Base
In this method, we calculate the height of a triangle if we know its area and the length of the base.
# Method 1: Using Area and Base def calculate_height_from_area_and_base(area, base): return (2 * area) / base # Example usage triangle_area = 20 triangle_base = 10 triangle_height = calculate_height_from_area_and_base(triangle_area, triangle_base) print("Area of the triangle:", triangle_area) print("Base of the triangle:", triangle_base) print("Height of the triangle:", triangle_height)
Output:
Area of the triangle: 20 Base of the triangle: 10 Height of the triangle: 4.0
Method 2: Using Heron’s Formula
Heron’s formula can be used to calculate the area of a triangle when the lengths of all three sides are known. Once we have the area, we can use the method from the previous section to find the height.
import math def calculate_area_heron(a, b, c): s = (a + b + c) / 2 return math.sqrt(s * (s - a) * (s - b) * (s - c)) def calculate_height_from_sides(a, b, c): area = calculate_area_heron(a, b, c) base = a # You can use any side as the base return (2 * area) / base # Example usage side1 = 5 side2 = 6 side3 = 7 triangle_height = calculate_height_from_sides(side1, side2, side3) print("Sides of the triangle:", side1, side2, side3) print("Height of the triangle (using side1 as base):", triangle_height)
Output:
Sides of the triangle: 5 6 7 Height of the triangle (using side1 as base): 4.476527870832405