TAGS :Viewed: 5 - Published at: a few seconds ago

[ How to find way to stop while loop when 1 first point meet last in polygon in python? ]

I need to calculate the perimeter of a polygon by using only coordinates.

My function:

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" *

gives wrong Perimeter (compared to ArcGIS).

How to find way to stop while loop when 1 first point meet last in polygon in python?

Answer 1


You don't really need a while loop here. You can do it with a for loop since you are going through all of the polygon's vertices:

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))

If you insist on doing so with a while loop you can do so in this way:

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))

Answer 2


Your algorithm is not correct. You need to first sort your coordinates based on the arctangent of the angle they create with the centroid of your polygon. (In order to get the correct order of your coordinates in your shape)

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))

Then you can calculate the length of the sides of shape using pair coordinates and sum up all them to get the perimeter:

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:]))

Answer 3


Seeing your while loop condition, I am guessing your last and first coordinates are the same.

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

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

I don't see any other way in which that while loop condition makes sense. If it is so, then you should try.

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