鞋带配方的最快方法 [英] Fastest way to Shoelace formula
本文介绍了鞋带配方的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我做了一个用鞋带方式计算面积多边形的函数.
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.
我的功能:
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.
我的多边形:
polygonBoundary = ((5, 0), (6, 4), (4, 5), (1, 5), (1, 0))
结果:
22.
有什么想法吗?
我尝试使用 Numpy :这是最快的,但你必须先转换你的坐标.
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,你必须在鞋带方法中发送一个 (x,y) 坐标的 numpy 数组作为参数:>
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
这篇关于鞋带配方的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文