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: 3 additions & 1 deletion spatialmath/base/quaternions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
27 changes: 27 additions & 0 deletions tests/test_qangle_shortest.py
Original file line number Diff line number Diff line change
@@ -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)