Area of a triangle

Area of a triangle

Introduction

  • Given a triangle: picture of a triangle with vertices: (0, 0), (8, 0), and (6, 6)
  • We can calculate it's area using the formula: equation of area of a triangle where:
    • b: The base of the triangle.
    • h: The height of the triangle.
  • For this triangle:
    • b = 8
    • h = 6
    • 8 * 6 / 2 = 24

Code (Python)

vertices = [[0, 0], [8, 0], [6, 6]]

# stores the two vertices used for calculating the base
baseVertices = None

# tracks the axis used for the base vertices
# 0 for a change in x, 1 for a change in y
axis = None

for i in [0, 1]:
    for j in [i + 1, 2]:
        if vertices[i][0] == vertices[j][0]:
            baseVertices = [i, j]
            # if the vertices are the same in the x-axis
            # then they are different in the y-axis
            axis = 1
            break
        elif vertices[i][1] == vertices[j][1]:
            baseVertices = [i, j]
            # if the vertices are the same in the y-axis
            # then they are different in the x-axis
            axis = 0
            break

if baseVertices is None:
    raise Exception("Triangle does not have perpendicular base and height")

base = vertices[baseVertices[0]][axis] - vertices[baseVertices[1]][axis]
base = abs(base)

# find the vertex that isn't used in calculating the base
for a in [0, 1, 2]:
    if a != baseVertices[0] and a != baseVertices[1]:
        otherVertex = a
        break

invertedAxis = 1 - axis

# calculate the height
height = vertices[baseVertices[0]][invertedAxis] - vertices[otherVertex][invertedAxis]
height = abs(height)

area = base * height / 2
print(area) # prints 24.0

Notes

  • The base must be perpendicular to the height.
    • For the below triangle: triangle without a perpendicular base and height
    • We cannot easily calculate the base and height as they are not at right angles.
    • Other methods can be used for these cases.