如何用Python找到在多边形中首尾相遇时停止循环的方法?

2024-09-29 23:29:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我只需要用坐标来计算多边形的周长。你知道吗

我的职能:

def definePerimeter(xCoords, yCoords):

i = 0
sum = 0
while xCoords[i] != xCoords[i+1] and yCoords[i] != yCoords[i+1]:
    dx = xCoords[i] - xCoords[i+1]
    dy = yCoords[i] - yCoords[i+1]
    dsquared = dx**2 + dy**2
    result = math.sqrt(dsquared)
    print "The list of segments:"
    print "The segment: ", result
    i += 1
    sum = sum + result           
print  "Total 2D Perimeter is " , sum ,"m" *

给出了错误的周长(与ArcGIS相比)。你知道吗

在python的多边形中,当第一个点最后一次相遇时,如何找到停止循环的方法?你知道吗


Tags: thedefresult多边形sumprint职能while
3条回答

看到你的while循环条件,我猜你的最后和第一个坐标是一样的。你知道吗

x = [0,1,2,3,0]

y = [0,2,4,5,0]

我看不出while循环条件有任何其他意义。如果是这样,那你应该试试。你知道吗

i = math.fmod((i+1),len(xCoords))

这里不需要while循环。您可以使用for循环来完成,因为您要遍历多边形的所有顶点:

sum = 0
for i in xrange(len(xCoords) - 1):
      sum += np.sqrt((xCoords[i] - xCoords[i + 1]) ** 2) + (yCoords[i] -yCoords[i + 1]) ** 2))
sum+=np.sqrt((xCoords[0] - xCoords[-1]) ** 2) + (yCoords[0] -yCoords[-1]) ** 2))

如果您坚持使用while循环执行此操作,您可以这样做:

sum = 0
i = 0
while (i < len(xCoords) - 1):
          sum += np.sqrt((xCoords[i] - xCoords[i + 1]) ** 2) + (yCoords[i] -yCoords[i + 1]) ** 2))
          i += 1
sum+=np.sqrt((xCoords[0] - xCoords[-1]) ** 2) + (yCoords[0] -yCoords[-1]) ** 2))

你的算法不正确。首先需要根据坐标与多边形质心所形成角度的反正切对坐标进行排序。(以获得形状中坐标的正确顺序)

from math import atan

def sort_coordinates(centroid, shuffled_coordinates):
    Cx, Cy = centroid
    return sorted(shuffled_coordinates, key=lambda p: math.atan2(p[1]-Cy,p[0]-Cx))

然后,可以使用对坐标计算形状边的长度,并将所有边相加以获得周长:

def perimeter(coordinates):
    return sum(math.sqrt(pow(y2-y1,2)+pow(x2-x1,2)) for (x1,y1),(x2,y2) in zip(coordinates, coordinates[1:]))

相关问题 更多 >

    热门问题