Python – Is there a method to calculate the signed area of a polygon?

Question:

I have a polygon defined in a Python list with (x, y) coordinates.

# for example
polygon = [(0, 0), (2, 0), (2, 2), (1, 1), (0, 2)]

I would like to get the signed area of this polygon. I know I could write my own algorithm to do it, but I’m searching for an existing method which does the same thing.

I’ve already read the following post : Calculate area of polygon given (x,y) coordinates but it only talks about getting the area, which differs from the signed area.

Asked By: Coquelicot

||

Answers:

To calculate the signed area of a polygon, you can use the shoelace formula. this code:

polygon = [(0, 0), (2, 0), (2, 2), (1, 1), (0, 2)]

def signed_polygon_area(polygon):
    n = len(polygon)
    area = 0.0
    for i in range(n):
        j = (i + 1) % n
        area += polygon[i][0] * polygon[j][1]
        area -= polygon[j][0] * polygon[i][1]
    return 0.5 * area

 print(signed_polygon_area(polygon)) --> 3.0
Answered By: Miladfa7
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.