Calculating Triangle Area with Heron#s Formula

  • Share this:

Code introduction


This function calculates the area of a triangle using Heron's formula, which is a method to calculate the area of a triangle when its three side lengths are known.


Technology Stack : math - Provides mathematical functions such as square root and power.

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import random
import math

def calculate_random_triangle_area(side1, side2):
    """
    Calculate the area of a triangle using Heron's formula.

    :param side1: Length of the first side of the triangle.
    :param side2: Length of the second side of the triangle.
    :return: The area of the triangle.
    """
    # Calculate the semi-perimeter of the triangle
    s = (side1 + side2 + math.sqrt(side1**2 + side2**2)) / 2

    # Calculate the area using Heron's formula
    area = math.sqrt(s * (s - side1) * (s - side2) * (s - math.sqrt(side1**2 + side2**2)))

    return area