Skip to content

added shoelace formula, computing the area of a simple polygon #12117

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,7 @@

## Geometry
* [Geometry](geometry/geometry.py)
* [Shoelace](geometry/shoelace.py)

## Graphics
* [Bezier Curve](graphics/bezier_curve.py)
Expand Down
33 changes: 33 additions & 0 deletions geometry/shoelace.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from typing import List

Check failure on line 1 in geometry/shoelace.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP035)

geometry/shoelace.py:1:1: UP035 `typing.List` is deprecated, use `list` instead


def area_of_polygon(xs: List[float], ys: List[float]) -> float:

Check failure on line 4 in geometry/shoelace.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

geometry/shoelace.py:4:25: UP006 Use `list` instead of `List` for type annotation

Check failure on line 4 in geometry/shoelace.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

geometry/shoelace.py:4:42: UP006 Use `list` instead of `List` for type annotation
"""
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
ys: list of y coordinates of the polygon vertices
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()
Loading