From c269d512c63dd6030ded33bebd1f864bc4731bfe Mon Sep 17 00:00:00 2001 From: Ranjith Guggilla Date: Fri, 27 Nov 2026 21:11:43 -0600 Subject: [PATCH] fix(base): trlog loses accuracy for rotations just below pi trlog computed the rotation angle as acos((trace(R) - 1) / 2). Close to a half turn acos is ill-conditioned, so for pi - 1e-7 the angle was off by up to 0.1 rad and could be larger than pi. The axis was then scaled by sin of that wrong angle. tr2angvec, SO3.angvec, SE3.log and Twist3(SE3) all go through this code. Take the angle from atan2(|vex(R - R^T)| / 2, (trace(R) - 1) / 2) instead, which is accurate for every angle, and normalise the axis by the same sine. The exact-pi branch is unchanged. --- spatialmath/base/transforms3d.py | 8 +++++--- tests/base/test_transforms3d.py | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/spatialmath/base/transforms3d.py b/spatialmath/base/transforms3d.py index 5c90b636..ac02be4b 100644 --- a/spatialmath/base/transforms3d.py +++ b/spatialmath/base/transforms3d.py @@ -1409,9 +1409,11 @@ def trlog( else: # general case tr = (np.trace(R) - 1) / 2 - # min for inaccuracies near identity yielding trace > 3 - theta = math.acos(min(tr, 1.0)) - st = math.sin(theta) + # sin(theta) from the skew-symmetric part, cos(theta) from the trace. + # atan2 of the two is accurate for every angle, acos(tr) alone loses + # precision close to pi (and close to 0). + st = norm(vex(R - R.T)) / 2 + theta = math.atan2(st, tr) if st == 0: if twist: return np.zeros((3,)) diff --git a/tests/base/test_transforms3d.py b/tests/base/test_transforms3d.py index 88ca96a1..af021362 100755 --- a/tests/base/test_transforms3d.py +++ b/tests/base/test_transforms3d.py @@ -375,6 +375,29 @@ def test_trlog_near_identity(self): v = trlog(R, twist=True) nt.assert_almost_equal(np.linalg.norm(v), theta, decimal=12) + def test_trlog_near_pi(self): + # Just below a half turn, acos((trace(R) - 1) / 2) loses most of its + # digits: before the fix the angle was off by up to 0.1 rad at + # pi - 1e-7 and could come out larger than pi. + axis = np.r_[1.0, 2.0, 3.0] / np.sqrt(14) + for delta in (1e-5, 1e-6, 3e-7, 1e-7): + theta = pi - delta + R = angvec2r(theta, axis) + + v = trlog(R, twist=True) + nt.assert_almost_equal(np.linalg.norm(v), theta, decimal=12) + nt.assert_array_almost_equal(v / np.linalg.norm(v), axis, decimal=8) + nt.assert_array_almost_equal(trexp(v), R, decimal=8) + + angle, vec = tr2angvec(R) + nt.assert_almost_equal(angle, theta, decimal=12) + nt.assert_array_almost_equal(vec, axis, decimal=8) + + # same rotation inside an SE(3) matrix + T = rt2tr(R, [1, 2, 3]) + w = trlog(T, twist=True)[3:] + nt.assert_almost_equal(np.linalg.norm(w), theta, decimal=12) + def test_trexp(self): R = trexp(skew([0.5, 0, 0])) nt.assert_array_almost_equal(R, rotx(0.5))