python – Fastest way to Shoelace formula

python – Fastest way to Shoelace formula

For me the fastest way would be using numpy where you have to send a numpy array of (x,y) cordinates as an argument in shoelace method:

import numpy as np
def shoelace(x_y):
    x_y = np.array(x_y)
    x_y = x_y.reshape(-1,2)

    x = x_y[:,0]
    y = x_y[:,1]

    S1 = np.sum(x*np.roll(y,-1))
    S2 = np.sum(y*np.roll(x,-1))

    area = .5*np.absolute(S1 - S2)

    return area

Heres a version that uses 1/2 as many multiplications: https://stackoverflow.com/a/717367/763269

If you need even greater performance, you could consider doing this in a Python C extension. C can be dramatically faster than Python, especially for math operations — sometimes 100-1000x.

python – Fastest way to Shoelace formula

Another interesting approach (although slower)

m = np.vstack([x,y])
result = 0.5 * np.abs(np.linalg.det(as_strided(m, (m.shape[1]-1, 2, 2), (m.itemsize, m.itemsize*m.shape[1], m.itemsize))).sum())

Leave a Reply

Your email address will not be published. Required fields are marked *