diff --git a/DIRECTORY.md b/DIRECTORY.md index 7761f7a23f2a..29183f42a94e 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -549,6 +549,7 @@ * [Ramer Douglas Peucker](geometry/ramer_douglas_peucker.py) * [Rotating Calipers](geometry/rotating_calipers.py) * [Segment Intersection](geometry/segment_intersection.py) + * [Shoelace](geometry/shoelace.py) * Tests * [Test Graham Scan](geometry/tests/test_graham_scan.py) * [Test Jarvis March](geometry/tests/test_jarvis_march.py) @@ -817,6 +818,7 @@ * [Monte Carlo](maths/monte_carlo.py) * [Monte Carlo Dice](maths/monte_carlo_dice.py) * [Ncr Combinations](maths/ncr_combinations.py) + * [Next Prime Number](maths/next_prime_number.py) * [Number Of Digits](maths/number_of_digits.py) * Numerical Analysis * [Adams Bashforth](maths/numerical_analysis/adams_bashforth.py) diff --git a/geometry/shoelace.py b/geometry/shoelace.py new file mode 100644 index 000000000000..a00f116b47ce --- /dev/null +++ b/geometry/shoelace.py @@ -0,0 +1,30 @@ +def area_of_polygon(xs: list[float], ys: list[float]) -> float: + """ + Compute the area of a polygon. The polygon has to be planar and simple + (not self-intersecting). The vertices have to be ordered in the + counter-clockwise direction. + https://en.wikipedia.org/wiki/Shoelace_formula + + Args: + xs: list of x coordinates of the polygon vertices in counter-clockwise order + ys: list of y coordinates of the polygon vertices in counter-clockwise order + Returns: + area of the polygon + + >>> from math import isclose + >>> xs = [1, 3, 7, 4, 8] + >>> ys = [6, 1, 2, 4, 5] + >>> isclose(area_of_polygon(xs, ys), 16.5) + True + """ + + return 0.5 * sum( + (ys[i] + ys[(i + 1) % len(ys)]) * (xs[i] - xs[(i + 1) % len(xs)]) + for i in range(len(xs)) + ) + + +if __name__ == "__main__": + import doctest + + doctest.testmod()