From d70109f2af73d1c5d289d80e0da8a67502c25317 Mon Sep 17 00:00:00 2001 From: Kaushik Gunasekaren Date: Sat, 14 Nov 2026 10:37:07 -0700 Subject: [PATCH 1/2] Use the shortest sign-invariant quaternion rotation angle Refactor quaternion distance calculation to use min and max of differences. --- spatialmath/base/quaternions.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/spatialmath/base/quaternions.py b/spatialmath/base/quaternions.py index 6800ff53..f226fc38 100755 --- a/spatialmath/base/quaternions.py +++ b/spatialmath/base/quaternions.py @@ -1168,7 +1168,9 @@ def qangle(q1: ArrayLike4, q2: ArrayLike4) -> float: q1 = smb.getvector(q1, 4) q2 = smb.getvector(q2, 4) - return 4.0 * math.atan2(smb.norm(q1 - q2), smb.norm(q1 + q2)) + difference = smb.norm(q1 - q2) + total = smb.norm(q1 + q2) + return 4.0 * math.atan2(min(difference, total), max(difference, total)) def q2str( From ca46c80529aeec276e7cb5a03aa8871d2c032c37 Mon Sep 17 00:00:00 2001 From: Kaushik Gunasekaren Date: Sat, 14 Nov 2026 10:37:30 -0700 Subject: [PATCH 2/2] Test shortest quaternion distances under sign changes --- tests/test_qangle_shortest.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 tests/test_qangle_shortest.py diff --git a/tests/test_qangle_shortest.py b/tests/test_qangle_shortest.py new file mode 100644 index 00000000..ef8ea8a1 --- /dev/null +++ b/tests/test_qangle_shortest.py @@ -0,0 +1,27 @@ +"""Quaternion sign cannot change the shortest rotation distance.""" + +import numpy as np +import pytest +from spatialmath.base import qangle + + +@pytest.mark.parametrize("theta", [0, 0.3, 2.0, np.pi]) +@pytest.mark.parametrize("signs", [(1, 1), (1, -1), (-1, 1), (-1, -1)]) +def test_shortest_angle_is_sign_invariant(theta, signs): + # Unit quaternions about the same oblique axis, with known separation. + axis = np.array([1, -2, 3], dtype=float) / np.sqrt(14) + start = 0.7 + first = np.r_[np.cos(start / 2), np.sin(start / 2) * axis] + second = np.r_[np.cos((start + theta) / 2), np.sin((start + theta) / 2) * axis] + first *= signs[0] + second *= signs[1] + assert qangle(first, second) == pytest.approx(theta, abs=1e-14) + assert qangle(second, first) == pytest.approx(theta, abs=1e-14) + + +@pytest.mark.parametrize("theta", [1e-10, 2 * np.pi - 0.2, 2 * np.pi]) +def test_angle_uses_shortest_equivalent_rotation(theta): + first = [1, 0, 0, 0] + second = [np.cos(theta / 2), np.sin(theta / 2), 0, 0] + expected = min(theta, 2 * np.pi - theta) + assert qangle(first, second) == pytest.approx(expected, abs=1e-14)