Search code examples
pythonpolygonarea

Python - area of irregular polygon results in negative value?


Good morning all! I have to calculate the area of a polygon using python. The formula to do that is given by (sorry, can't post pictures yet..)

(x0*y1 - y0*x1) + (x1*y2 - y1*x2) + ... + (xn-1*y0 - yn-1*x0)


2

This is the code i came up with. However, it results in a (correct) negative value, and i have no idea why. Would it be valid to simply multiply the area time -0.5 or is there something wrong with my code? Any help is greatly appreciated!!

polygon = [[0,0],[-1,5],[2,3],[1,5],[3,6],[4,5],[5,3],[8,-2],[4,-4],[2,-5]]
area = 0.0

n = len(polygon)
for i in range(n):
    i1 = (i+1)%n
    area += polygon[i][0]*polygon[i1][1] - polygon[i1][0]*polygon[i][1]       
area *= 0.5
print 'area = ', area

Solution

  • The formula works by computing a sum of the cross products of each pair of vectors between the origin and each end of the line segment composing the polygon. In essence, the area is computed as the difference between the area of the green and red triangles in the picture below. (Note that the red triangles are partially underneath the green ones.)

    illustration

    The sign of the cross product depends on the orientation of the vectors, i.e. if we can make the second vector to align with the first by turning it left or right. Therefore, you will get either a negative or positive area depending on whether the points in the polygon are ordered clockwise or counter-clockwise. The solution is correct, but you need to apply the abs() function to the result, since you don't need the sign.