Problem

An arbitrary triangle can be described by the coordinates of its three vertices: $(x1,y1),(x2,y2),(x3,y3)$, numbered in a counterclockwise direction. The area of the triangle is given by the formula,

\[A = \frac{1}{2} \bigg| x2y3 - x3y2 - x1y3 + x3y1 + x1y2 - x2y1 \bigg|\]
MATLAB

Write a function getTriangleArea(vertices) that returns the area of a triangle whose vertices are specified by the input argument variable vertices. The type of the input argument is the programmer’s choice. For example, it could be a cell array or a matrix.

Python

Write a function get_triangle_area(vertices) that returns the area of a triangle whose vertices are specified by the input argument variable vertices, which could be a nested list of the vertex coordinates. Test your implementation with the following test function, which also illustrates how the get_triangle_area function works.

def test_get_triangle_area():
    """
    Verify the area of a triangle with vertex coordinates
    (0,0), (1,0), and (0,2).
    """
    v1 = (0,0); v2 = (1,0); v3 = (0,2)
    vertices = [v1, v2, v3]
    expected = 1
    computed = get_triangle_area(vertices)
    tol = 1E-14
    success = abs(expected - computed) < tol
    msg = 'computed area=%g != %g (expected)' % (computed, expected)
    assert success, msg

Comments