Copied, by author from "Paddy3118 Go deh!: Python investigation of the Shoelace Formula for polygonal area http://paddy3118.blogspot.com/2017/07/python-investigation-of-shoelace.html#ixzz4n43Dqhaa " Where there is more meat on the bone (under a different license though).
1 2 3 4 | def area_by_shoelace(x, y):
"Assumes x,y points go around the polygon in one direction"
return abs( sum(i * j for i, j in zip(x, y[1:])) + x[-1] * y[0]
-sum(i * j for i, j in zip(x[1:], y)) - x[0] * y[-1]) / 2
|
I came across the formula and wanted to see how indexing would work out. Some articles had suggested rotating one of the x or y coords then doing an element-wise multiply then a sum; all of which numpy can do, but I wanted to see how Python without numpy would work.
On formatting, there is a deliberate extra space inserted in front of the first sum, visually highlighting the minus sign in front of the sum on the line below.
Should work with Python 2.7 if the 2 is replaced by 2.0 Should also work with rationals, decimals and complex numbers too.
Hmm, instead of writing:
I could have written:
There's not much difference to look at.