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
8 changes: 5 additions & 3 deletions spatialmath/base/transforms3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,))
Expand Down
23 changes: 23 additions & 0 deletions tests/base/test_transforms3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down