Start free

Expert · Geometry · 263 of 264

Area of a polygon

Compute the area of a simple polygon from its corners (in order around the edge) with the shoelace formula. Print it with one decimal.

Input: n, then n lines "x y". Output: the area, one decimal.

Examples

Input
4
0 0
4 0
4 3
0 3
Output
12.0
Input
3
0 0
1 0
0 1
Output
0.5
Input
5
0 0
4 0
4 4
2 2
0 4
Output
12.0

One more test checks other inputs when you press Check.

Stuck? The idea behind 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.0

Watch for: Decimals add up small errors: keep whole numbers as long as you can and compare with care.

All the geometry exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More geometry exercises