Compare commits

...

3 Commits

Author SHA1 Message Date
simin75simin
4e199aefa7
Merge cb2ad85223 into 3e9ca92ca9 2024-11-05 18:06:36 +01:00
simin75simin
cb2ad85223 updating DIRECTORY.md 2024-10-16 14:02:34 +00:00
siminsimin
fac0d7dba8 Compute the area of a polygon. 2024-10-16 22:02:13 +08:00
2 changed files with 31 additions and 0 deletions

View File

@ -457,6 +457,7 @@
## Geometry ## Geometry
* [Geometry](geometry/geometry.py) * [Geometry](geometry/geometry.py)
* [Shoelace](geometry/shoelace.py)
## Graphics ## Graphics
* [Bezier Curve](graphics/bezier_curve.py) * [Bezier Curve](graphics/bezier_curve.py)

30
geometry/shoelace.py Normal file
View File

@ -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()