Skip to content
Open
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
4 changes: 2 additions & 2 deletions spatialmath/geom2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -1130,7 +1130,7 @@ def polygon(self, resolution=10) -> Polygon2:
"""
Approximate with a polygon

:param resolution: number of polygon vertices, defaults to 20
:param resolution: number of polygon vertices, defaults to 10
:type resolution: int, optional
:return: a polygon approximating the ellipse
:rtype: :class:`Polygon2` instance
Expand All @@ -1148,7 +1148,7 @@ def polygon(self, resolution=10) -> Polygon2:

:seealso: :meth:`points`
"""
return Polygon2(smb.ellipse(self.E, self.centre, resolution=resolution - 1))
return Polygon2(smb.ellipse(self.E, self.centre, resolution=resolution))


if __name__ == "__main__":
Expand Down
29 changes: 29 additions & 0 deletions tests/test_ellipse_polygon_regression.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import numpy as np
import numpy.testing as nt
import pytest
from spatialmath import Ellipse


@pytest.mark.parametrize("resolution", [3, 4, 5, 10, 20, 51])
@pytest.mark.parametrize(
"radii,theta,centre",
[((1, 1), 0, (0, 0)), ((1, 2), 0.6, (3, -4)), ((3, 0.5), -0.4, (-2, 1))],
)
def test_ellipse_polygon_vertex_count(resolution, radii, theta, centre):
ellipse = Ellipse(radii=radii, theta=theta, centre=centre)
polygon = ellipse.polygon(resolution=resolution)
vertices = polygon.vertices()
assert len(polygon) == resolution
assert vertices.shape == (2, resolution)
closed = polygon.vertices(unique=False)
assert closed.shape == (2, resolution + 1)
nt.assert_array_equal(closed[:, 0], closed[:, -1])
nt.assert_allclose(vertices, ellipse.points(resolution=resolution))
offsets = vertices - np.array(centre)[:, None]
nt.assert_allclose(np.einsum("in,ij,jn->n", offsets, ellipse.E, offsets), 1)
expected_area = resolution * np.prod(radii) * np.sin(2 * np.pi / resolution) / 2
assert polygon.area() == pytest.approx(expected_area)


def test_ellipse_polygon_default_resolution():
assert len(Ellipse(E=np.eye(2)).polygon()) == 10