Beyond A level · 2 exercises
Python geometry
Points as (x, y) pairs. The cross product of two vectors says which way they turn: positive left, negative right, zero in line.
The shoelace formula gives a polygon's area from its corners in order.
pts = [(0, 0), (4, 0), (4, 3)]
area = 0
for i in range(len(pts)):
x1, y1 = pts[i]
x2, y2 = pts[(i + 1) % len(pts)]
area += x1 * y2 - x2 * y1
print(abs(area) / 2) # 6.0Watch for: Decimals add up small errors: keep whole numbers as long as you can and compare with care.
Exercises
- Area of a polygonCompute the area of a simple polygon from its corners (in order around the edge)Expert
- Fence around the treesBuild the smallest convex fence around all the trees (the convex hull).Expert