This code uses Simpson's rule , but gives the wrong area of a polygon by the formula:
def defineArea(xCoords, yCoords):
i = 0
sum = 0
for i in xrange(len(xCoords) - 1):
result = (xCoords[i] - xCoords[i+1])*(yCoords[i]+ yCoords[i+1])
i +=1
sum = 0.5*(sum + result)
print "Total 2D area is: ", sum*
What I am doing wrong? How do I calculate the area of polygon by Simpson's rule using only coordinates?
Don't do sum = 0.5*(sum + result)
inside the loop. Also, you don't need the sum
variable at all once it's outside the loop. Just do result = 0.5 * result
after the loop is complete, then print result
.
You also need to switch the order of xCoords[i]
and xCoords[i+1]
.
Do what "Bill the Lizard" said (sorry I can't post a comment yet), or you can do it inside the loop too:
sum = sum + 0.5*result
Also, you are doing (xCoords[i] - xCoords[i+1])
instead of (xCoords[i+1] - xCoords[i])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.