I have made a function who calculate area polygon with Shoelace way.
That's works perfectly but right now I wonder if there is not a faster way to have the same result. I want to know that because this function must work faster with polygon with a lot of coordinates.
My function :
def shoelace_formula(polygonBoundary, absoluteValue = True):
nbCoordinates = len(polygonBoundary)
nbSegment = nbCoordinates - 1
l = [(polygonBoundary[i+1][0] - polygonBoundary[i][0]) * (polygonBoundary[i+1][1] + polygonBoundary[i][1]) for i in xrange(nbSegment)]
if absoluteValue:
return abs(sum(l) / 2.)
else:
return sum(l) / 2.
My polygon :
polygonBoundary = ((5, 0), (6, 4), (4, 5), (1, 5), (1, 0))
Result :
22.
Any ideas?
I try with Numpy : It's speedest but you have to convert your coordinates first.
import numpy as np
x, y = zip(*polygonBoundary)
def shoelace_formula_3(x, y, absoluteValue = True):
result = 0.5 * np.array(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))
if absoluteValue:
return abs(result)
else:
return result
numpy
should help. https://mcmap.net/q/102332/-calculate-area-of-polygon-given-x-y-coordinates – Bonaventureshoelace_formula_3
was twice as fast (115 microseconds) asshoelace_formula
(321 microseconds). – Bonaventurex, y = zip(*polygonBoundary)
outside of the function and includex
andy
as function parameters, it runs in 93.7 microseconds. And importnumpy
outside of the function. – Bonaventure0.5 * np.abs(np.dot(x[:-1], y[1:]) + x[-1]*y[0] - np.dot(y[:-1], x[1:]) - y[-1]*x[0])
– Merth