最快的鞋带配方方法

Gui*_*ain 4 python performance polygon area

我做了一个用鞋带方式计算面积多边形的函数。

这非常有效,但现在我想知道是否没有更快的方法来获得相同的结果。我想知道这一点,因为这个函数对于具有大量坐标的多边形必须运行得更快。

我的职能:

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.
Run Code Online (Sandbox Code Playgroud)

我的多边形:

polygonBoundary = ((5, 0), (6, 4), (4, 5), (1, 5), (1, 0))
Run Code Online (Sandbox Code Playgroud)

结果 :

22.
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

我尝试使用 Numpy :它速度最快,但您必须先转换坐标。

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
Run Code Online (Sandbox Code Playgroud)

Mus*_*han 6

对我来说,最快的方法是使用 numpy,其中您必须发送 (x,y) 坐标的 numpy 数组作为鞋带方法中的参数:

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
Run Code Online (Sandbox Code Playgroud)