Calculate the area of a triangle when all the three sides are known using Heron's Formula in Python.

Hey CodeSpeeder!

Ever got bored of using angles and distances first for calculating the area of a triangle?

Well, thanks to the Hero of Alexandria!

He gave a simple formula to calculate the area of a triangle when all the three sides are known to us.

The formula was named after him as "**Heron's Formula**".

Look at this figure! All the lengths of the three sides of a triangle **a**, **b**, and **c** are given.

The **area A of a triangle** is given by:

Here,

a: length of side 1

b: length of side 2

c: length of side 3

s: semi-perimeter of the triangle

A: area of the triangle

Let's now code a small **python** implementation for calculating the area of the triangle using Heron's formula!

import math # function to calculate the area of a triangle # when its three sides a, b, and c are given def areaOfTriangle(a, b, c): # s is the semi-perimeter of the triangle s = (a + b + c) / 2 product = s * (s - a) * (s - b) * (s - c) # product >= means triangle can be formed with the given sides if product > 0: # Calculate area using Heron's Formula area = math.sqrt(product) # when the triangle can't be formed with the given sides, area=0 else: area = 0 return area

Now let's check the function **areaOfTriangle()** on various test-cases!

sides = [(3, 4, 5), (13, 4, 15), (4, 4, 4), (4, 4, 2), (1, 2, 3)] for (a, b, c) in sides: print("Area of the triangle with sides a=", a, "units, b=", b, "units, and c=", c, "units is ", round(areaOfTriangle(a, b, c), 3),"units^2.")

Run the above code and you'll get the following output.

Area of the triangle with sides a= 3 units, b= 4 units, and c= 5 units is 6.0 units^2. Area of the triangle with sides a= 13 units, b= 4 units, and c= 15 units is 24.0 units^2. Area of the triangle with sides a= 4 units, b= 4 units, and c= 4 units is 6.928 units^2. Area of the triangle with sides a= 4 units, b= 4 units, and c= 2 units is 3.873 units^2. Area of the triangle with sides a= 1 units, b= 2 units, and c= 3 units is 0 units^2.

Look at the test-case 1. It's a right angles triangle with two sides of length 3 and 4 units and a hypotenuse of length 5 units. The area is 6 unit^{2}.

It's the only triangle with consecutive integral side-lengths and area.

Let the consecutive integer sides be d-1, d, d+1 and the area be d+2.

Area using heron's formula A will be

Equating and solving A = d+2.

Submitted by Kalki Pareshkumar Bhavsar (KalkiBhavsar)

Download packets of source code on Coders Packet

## Comments