Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Preserve scaled quaternion rotations in logarithms
  • Loading branch information
dddd-jh authored and taughz committed Oct 13, 2026
commit 0f7cf491f57101f3d3b69fb8fc7d42698991f6c4
21 changes: 10 additions & 11 deletions spatialmath/quaternion.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,9 @@ def log(self) -> Quaternion:

\ln \| q \|, \langle \frac{\vec{v}}{\| \vec{v} \|} \cos^{-1} \frac{s}{\| q \|} \rangle

The implementation uses the equivalent :math:`\operatorname{atan2}(\|\vec{v}\|, s)`
to avoid the loss of precision in ``acos`` for small rotation angles.

For a ``UnitQuaternion`` the logarithm is a pure quaternion whose vector
part :math:`\vec{v}` and :math:`\vec{v}/2` is a Euler vector: parallel
to the axis of rotation and whose norm is the magnitude of rotation.
Expand All @@ -403,21 +406,17 @@ def log(self) -> Quaternion:
norm = self.norm()
s = np.log(norm)
if len(self) == 1:
if smb.iszerovec(self._A[1:4]):
n = math.hypot(*self._A[1:4])
if n == 0:
v = np.zeros((3,))
else:
# atan2 retains small angles when s / norm rounds to one.
v = math.atan2(smb.norm(self._A[1:4]), self._A[0]) * smb.unitvec(
self._A[1:4]
)
v = math.atan2(n, self._A[0]) * self._A[1:4] / n
return Quaternion(s=s, v=v)
else:
v = [
np.zeros((3,))
if smb.iszerovec(A[1:4])
else math.atan2(smb.norm(A[1:4]), A[0]) * smb.unitvec(A[1:4])
for A in self._A
]
v = []
for A in self._A:
n = math.hypot(*A[1:4])
v.append(np.zeros((3,)) if n == 0 else math.atan2(n, A[0]) * A[1:4] / n)
return Quaternion(s=s, v=np.array(v))

def exp(self, tol: float = 20) -> Quaternion:
Expand Down
8 changes: 6 additions & 2 deletions tests/test_quaternion.py
Original file line number Diff line number Diff line change
Expand Up @@ -946,7 +946,7 @@ def test_log(self):
def test_log_small_rotation(self):
axis = np.array([1.0, -2.0, 3.0]) / math.sqrt(14)
for angle in (1e-12, -1e-9, 1e-7, 1e-4, 0.3):
for scale in (1.0, 3.0):
for scale in (1.0, 3.0, 1e-6):
with self.subTest(angle=angle, scale=scale):
values = scale * np.r_[cos(angle / 2), sin(angle / 2) * axis]
q = UnitQuaternion(values) if scale == 1 else Quaternion(values)
Expand All @@ -964,7 +964,11 @@ def test_log_small_rotation_sequence(self):
(np.cos(angles / 2), np.sin(angles[:, None] / 2) * axes)
)
expected = angles[:, None] / 2 * axes
for scales in (np.ones(4), np.array([2.0, 3.0, 4.0, 5.0])):
for scales in (
np.ones(4),
np.array([2.0, 3.0, 4.0, 5.0]),
1e-6 * np.ones(4),
):
with self.subTest(scales=scales):
scaled = scales[:, None] * values
q = (
Expand Down
Loading