Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The implementation of your formula is flawed. It looks ahead to values in your x, y lists that haven't been set yet with <code>(x[i]*y[i+1] - x[i+1]*y[i])</code></p> <p>If you put a print statement inside your try-except block you will see that you are simply multiplying by zero and getting zero area:</p> <pre><code>try: x[i], y[i] = polygon[i] area += (x[i]*y[i+1] - x[i+1]*y[i]) print x[i], y[i+1], x[i+1], y[i] except IndexError, e: return area/2 #1 0 0 2 #2 0 0 5 </code></pre> <p>Also, you are not returning the results of your recursive call to areaofpolygon, so you will never get that <code>area/2</code>. You want: <code>return areaofpolygon(polygon, i+1)</code>. And make sure you actually divide by 2.0 so that you get float precision since your points are ints.</p> <p>Try just using the formula you found or that was suggested in another question.</p> <p><strong>Update</strong></p> <p>Here is a fixed version of your code:</p> <pre><code>#!/usr/bin/env python from random import randint from shapely.geometry import Polygon area = 0 def areaofpolygon(polygon, i): global area if i == 0: area = 0 try: x1, y1 = polygon[i] x2, y2 = polygon[i+1] area += (x1*y2) - (x2*y1) except IndexError, e: x1, y1 = polygon[0] x2, y2 = polygon[-1] area += (x2*y1) - (x1*y2) return abs(area/2.0) return areaofpolygon(polygon, i+1) def main(): mypolygon = [(randint(0, 100), randint(0, 100)) for _ in xrange(10)] print mypolygon area = areaofpolygon(mypolygon, 0) assert area == Polygon(mypolygon).area print "Test passed." return 0 if __name__ == '__main__': main() ### Output ### $ ./test.py [(29, 76), (85, 49), (27, 80), (94, 98), (19, 1), (75, 6), (55, 38), (74, 62), (0, 25), (93, 94)] Test passed. $ ./test.py [(13, 37), (98, 74), (42, 58), (32, 64), (95, 97), (34, 62), (34, 59), (21, 76), (55, 32), (76, 31)] Test passed. $ ./test.py [(38, 67), (66, 59), (16, 71), (53, 100), (64, 52), (69, 31), (45, 23), (52, 37), (27, 21), (42, 74)] Test passed. </code></pre> <p>Notice that you didn't need global x,y lists. And you also missed the last part of the equation where you use the last point and the first point.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload