sazr
sazr

Reputation: 25928

Correct way to calculate triangle area from 3 vertices

Is this the correct way to calculate the area of a triangle given the 3 triangle points/vertices? The vertices will never be negative values.

def triangle_area(tri):
    x1, y1, x2, y2, x3, y3 = tri[0][0], tri[0][1], tri[1][0], tri[1][1], tri[2][0], tri[2][1]
    return 0.5 * (((x2-x1)*(y3-y1))-((x3-x1)*(y2-y1)))

Upvotes: 4

Views: 6270

Answers (3)

Martin Thoma
Martin Thoma

Reputation: 136339

If you want to calculate a triangles area, you can calculate the surrounding rectangles area and substract the 3 triangles which have 90° angles around it:

def triangle_area(tri):
    x_min = min([point[0] for point in tri])
    x_max = max([point[0] for point in tri])
    y_min = min([point[1] for point in tri])
    y_max = max([point[1] for point in tri])
    area_rectangle = (y_max - y_min) * (x_max - x_min)
    t1 = 0.5 * abs((tri[0][0] - tri[1][0]) * (tri[0][1] - tri[1][1]))
    t2 = 0.5 * abs((tri[0][0] - tri[2][0]) * (tri[0][1] - tri[2][1]))
    t3 = 0.5 * abs((tri[1][0] - tri[2][0]) * (tri[1][1] - tri[2][1]))
    return area_rectangle - t1 - t2 - t3

enter image description here

Alternatively, you can use Herons Formula

Upvotes: 0

dmuir
dmuir

Reputation: 4431

Almost, but you need to take the absolute value at the end. You're formula can be derived from the Shoelace formula which applies to any simple (no crossing edges, no holes) polygon.

Upvotes: 1

MBo
MBo

Reputation: 80187

It is necessary to add abs to this formula to avoid negative area value (sign depends on orientation, not on positive/negative coordinates)

Yes, this formula is correct and it implements the best approach if you have vertices coordinates. It is based on cross product properties.

def triangle_area(tri):
    x1, y1, x2, y2, x3, y3 = tri[0][0], tri[0][1], tri[1][0], tri[1][1], tri[2][0], tri[2][1]
    return abs(0.5 * (((x2-x1)*(y3-y1))-((x3-x1)*(y2-y1))))

Upvotes: 4

Related Questions