Skip to content

Commit baadf5e

Browse files
Geometry - shoelace formula (#12118)
* Compute the area of a polygon. * updating DIRECTORY.md * updating DIRECTORY.md --------- Co-authored-by: simin75simin <simin75simin@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: cclauss <cclauss@users.noreply.github.com>
1 parent 01963e0 commit baadf5e

2 files changed

Lines changed: 32 additions & 0 deletions

File tree

DIRECTORY.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -549,6 +549,7 @@
549549
* [Ramer Douglas Peucker](geometry/ramer_douglas_peucker.py)
550550
* [Rotating Calipers](geometry/rotating_calipers.py)
551551
* [Segment Intersection](geometry/segment_intersection.py)
552+
* [Shoelace](geometry/shoelace.py)
552553
* Tests
553554
* [Test Graham Scan](geometry/tests/test_graham_scan.py)
554555
* [Test Jarvis March](geometry/tests/test_jarvis_march.py)
@@ -817,6 +818,7 @@
817818
* [Monte Carlo](maths/monte_carlo.py)
818819
* [Monte Carlo Dice](maths/monte_carlo_dice.py)
819820
* [Ncr Combinations](maths/ncr_combinations.py)
821+
* [Next Prime Number](maths/next_prime_number.py)
820822
* [Number Of Digits](maths/number_of_digits.py)
821823
* Numerical Analysis
822824
* [Adams Bashforth](maths/numerical_analysis/adams_bashforth.py)

geometry/shoelace.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
def area_of_polygon(xs: list[float], ys: list[float]) -> float:
2+
"""
3+
Compute the area of a polygon. The polygon has to be planar and simple
4+
(not self-intersecting). The vertices have to be ordered in the
5+
counter-clockwise direction.
6+
https://en.wikipedia.org/wiki/Shoelace_formula
7+
8+
Args:
9+
xs: list of x coordinates of the polygon vertices in counter-clockwise order
10+
ys: list of y coordinates of the polygon vertices in counter-clockwise order
11+
Returns:
12+
area of the polygon
13+
14+
>>> from math import isclose
15+
>>> xs = [1, 3, 7, 4, 8]
16+
>>> ys = [6, 1, 2, 4, 5]
17+
>>> isclose(area_of_polygon(xs, ys), 16.5)
18+
True
19+
"""
20+
21+
return 0.5 * sum(
22+
(ys[i] + ys[(i + 1) % len(ys)]) * (xs[i] - xs[(i + 1) % len(xs)])
23+
for i in range(len(xs))
24+
)
25+
26+
27+
if __name__ == "__main__":
28+
import doctest
29+
30+
doctest.testmod()

0 commit comments

Comments
 (0)