shoelace

less than 1 minute read

Published:

Say you have a hole-less non intersecting “simple” type polygon with $n$ sides and you want to find its area. There are many ways to do this, typically dividing the polygon into shapes with small number of vertices. But the most elegant solution was proposed centuries ago and now known as the Shoelace method: \(\displaystyle \mathrm{Area}=\frac{1}{2}\Bigg|\Big(\sum_{i=1}^{n-1}x_iy_{i+1}+x_n y_1\Big) - \Big(\sum_{i=1}^{n-1}x_{i+1} y_i+x_1 y_n\Big)\Bigg|\)

with $x$ and $y$ being the coordinates of $n$ vertices. If you have the coordinates as one-dimensional arrays x and y, using the numpy.roll() function this can be implemented as a beautiful one-liner:

np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))) / 2.