The Area of a Triangle

There are several ways to compute the area of a triangle depending on what information is available.

For the purposes of method dispatch, we'll define a wrapper for our angles. Otherwise we'll have some ambiguity with respect to a function with three float inputs. This will make sense as you read on.

struct Angle
    θ::Float64
end

For any triangle, using the base, \(b\), and height, \(h\),

\[ A = \frac{1}{2}\cdot b \cdot h \,.\]
A(base::T, height::T) where {T<:Real} = 0.5 * base * height

Using the sides, \(a\), \(b\), and \(c\), where \(s = \frac{1}{2}(a + b + c)\),

\[ A = \sqrt{s ( s - a )(s - b)(s - c)}\,.\]
function A(a::T, b::T, c::T) where {T<:Real}
    s = (a + b + c)/2
    sqrt(s * (s - a) * (s - b) * (s - c))
end

Using the angle, \(\theta\), formed by two sides \(a\) and \(b\),

\[ A = \frac{1}{2} a b \sin \theta \,.\]
A(a::T, b::T, θ::Angle) where {T<:Real} = 0.5 * a * b * sin(θ.θ)

Suppose we have a triangle which has sides of length \(8\), \(8\), and \(12\).

Since we don't have the height, we need to compute it using the Pythagorean theorem as \(h = \sqrt{8^2 - \Big(\frac{12}{2}\Big)^2}\).

# Using 1/2 * base * height
A(12.0, sqrt(8^2 - (12/2)^2))
> 31.74901573277509

Using Heron's formula, we just plug in the value from each side.

A(8, 8, 12)
> 31.74901573277509

Using two sides and the angle formed between them. We'll need to compute the angle. We use the trigonometric relation \(b/2 = a\cos(\theta)\) resulting in \(\theta = \arccos{\frac{b}{2a}}\).

A(8, 12, Angle(acos(6/8)))
> 31.74901573277509

Three different formulas, one result.