3D rotations: SO(3), Euler angles, quaternions and the exponential map
Represent orientations with rotation matrices, Euler angles, axis-angle coordinates and unit quaternions. Derive Rodrigues' formula, understand gimbal lock and double coverage, and compare rotations with geodesic distance and spherical interpolation.
After this lesson you can
- Prove that rotation matrices form a group and have determinant one.
- Convert between matrices, Euler angles, axis-angle coordinates and unit quaternions with numerically stable code.
- Derive Rodrigues' formula as the exponential of a skew-symmetric matrix.
- Explain gimbal lock and the double coverage of SO(3) by unit quaternions.
- Calculate geodesic distance between rotations and interpolate using slerp.
Before you start
One orientation, several coordinate systems
A camera observes an object in its own frame; the robot must transform that observation to the gripper frame within the perception-action loop. An unnoticed change of convention can invert a rotation even when every number looks plausible. We use column vectors and active rotations: . To change coordinates between frames using the inverse operation, use .
The identity belongs to the set. If and belong to it, and . The inverse is , also orthogonal with determinant one. The product is associative because it is matrix multiplication. These properties prove that the set forms a group; they do not prove every orthogonal matrix has determinant one, since a reflection has determinant minus one. Composing applies first.
The nine matrix entries are not nine degrees of freedom. The columns have unit norm and are mutually orthogonal: six locally independent constraints leave three degrees of freedom. A matrix is redundant, but its composition and inverse are clear. Three angles are compact but do not provide a global chart without singularities. Four quaternion components add a unit-norm constraint and represent each orientation twice. Axis and angle are intuitive, but at zero angle the axis is undetermined and at its two signs are equivalent.
The determinant condition also has a geometric interpretation: the three columns are the transformed axes. Orthogonality ensures they still form an orthonormal basis. With determinant one they have the same handedness as the original basis; with determinant minus one they form a reflected basis. Rejecting a matrix that violates these conditions avoids mistaking a scaling or reflection for an orientation.
Three rings and a singularity
Euler angles and gimbal lock provide three local coordinates. Here we fix : roll , pitch , yaw . With active column vectors the rotation about fixed is applied first, then fixed , and finally fixed ; the equivalent interpretation uses moving axes in reverse order. The letters ZYX alone do not unambiguously specify every convention used by a library.
In world coordinates the columns of the angular-velocity Jacobian with respect to are , and . Its determinant has absolute value . At the third axis is : yaw and roll produce opposite velocities along the same line and the rank drops to two. The physical orientation still exists; this coordinate chart fails. Near lock, inverting the Jacobian amplifies errors.
That Jacobian relates parameter rates to angular velocity; its rank indicates how many independent instantaneous directions its columns generate.
For example, at 90° pitch, increasing yaw by a small amount and increasing roll by the same amount leaves orientation unchanged to first order because the two contributions cancel. The rank loss means this parametrization cannot recover three unique angular rates from an arbitrary angular velocity. It does not mean the robot has lost a physical joint or that rotation matrices are singular: every matrix in is invertible.
To reconstruct the angles away from the singularity, the entry gives on the branch . The pairs and give yaw and roll respectively using atan2. When , these pairs vanish: a library must fix one coordinate and return an equivalent solution. The proper check is therefore to reconstruct and compare the matrix, rather than require recovered angles to match the originals.
An axis and the exponential
For , define as the skew-symmetric matrix satisfying . The exponential map of SO(3) sends to , with . The set of skew-symmetric matrices is the algebra .
This is the same matrix exponential that solves the linear system of differential equations for constant angular velocity. In the plane perpendicular to the axis, the complex eigenvalues correspond to planar rotation.
Rodrigues’ axis-angle formula is
To derive it, write . The vector triple-product identity gives and hence . In the series for , odd powers sum to and nonconstant even powers sum to . Applied to , the formula produces the terms , and .
The principal logarithm returns with . For , and . Near zero use the local expansion; near division by is unstable, so obtain the axis from the symmetric part. At both axis signs describe the same rotation, so the logarithm is not unique. Clip the arccos argument to to tolerate rounding.
The skew-symmetric relation follows by subtracting the transpose of Rodrigues’ formula: . Near zero, the ratio tends to one, leaving approximately . Near , however, the skew-symmetric part vanishes even though the rotation is large. The symmetric part has the axis as an eigenvector with eigenvalue one. For an angle strictly below , the sign of the skew-symmetric part orients that eigenvector; exactly at either sign is valid.
The exponential map is not ordinary addition of orientations: in general . Rotations about different axes do not commute. Adding rotation vectors only approximates composition for sufficiently small perturbations, and its accuracy depends on both their magnitudes and directions.
Quaternions and distance
A unit quaternion is , with . Rotation about unit axis by angle corresponds to . The Hamilton product is
The conjugate is and for unit quaternions . The rotated vector is the vector part of . Both and give the same result: this is double coverage. After a 360° turn the body returns to its orientation, but the continuous representative moves from to ; returning to the initial quaternion takes 720°.
To see why the action does not distinguish signs, replace by : two minus signs appear, one on either side of , and cancel. Composition preserves the order of actions: applying and then is equivalent to the product . The Hamilton product is generally noncommutative, like multiplication of rotation matrices. Normalizing a nonzero four-component vector places it on the unit sphere, but does not by itself resolve a sign discontinuity in a time sequence.
Expanding the Hamilton product, the matrix associated with unit is . Substituting and recovers Rodrigues’ formula via double-angle identities. The formula also reveals the units: is dimensionless, while the angular velocity updating it is measured in radians per unit time. The zero quaternion represents no orientation and cannot be normalized.
The geodesic distance between rotations is the principal angle of , in . Since a rotation fixes its axis and turns the perpendicular plane, its trace is . Therefore . For unit quaternions it is also , with the product clipped to .
Spherical interpolation, or slerp, between unit representatives uses , where . If the product is negative, replace by to take the short orientation arc. For nearly equal representatives use normalized linear interpolation; if they are antipodal without correction the formula is indeterminate and infinitely many arcs exist. In the figure, at 360° the uncorrected arc uses the known axis as a limiting choice, not a unique solution.
Interpolation maintains unit norm and traverses the arc at constant angular velocity when advances uniformly. For a 180° difference in there are two equally short paths: reversing the axis sign changes the travel direction. An explicit tie-breaking policy prevents unexpected jumps at this boundary. Normalized linear interpolation is an approximation for small angles, not the same velocity parametrization for general separations.
Distance measures relative displacement, not the difference between nine entries. If both frames are rotated by the same matrix on the left, , so the relative angle remains unchanged. Subtracting two Euler triples can instead suggest a large error at a full-turn boundary even when orientations are close. An arithmetic mean of angles must likewise account for periodicity.
Lab: a small library
The following cell defines exponential, logarithm, conversions, distance and slerp. The functions expect valid rotation matrices, not arbitrary matrices. Near it uses the eigenvector of the symmetric part with the largest eigenvalue and orients its sign using the skew-symmetric part when possible.
import numpy as np
from scipy.spatial.transform import Rotation
def hat(v):
x, y, z = v
return np.array([[0., -z, y], [z, 0., -x], [-y, x, 0.]])
def vee(A):
return np.array([A[2, 1], A[0, 2], A[1, 0]])
def so3_exp(v):
v = np.asarray(v, dtype=float)
theta = np.linalg.norm(v)
A = hat(v)
if theta < 1e-6:
a, b = 1-theta**2/6, 0.5-theta**2/24
else:
a, b = np.sin(theta)/theta, (1-np.cos(theta))/theta**2
return np.eye(3) + a*A + b*(A@A)
def so3_log(R):
theta = np.arccos(np.clip((np.trace(R)-1)/2, -1, 1))
skew = vee(R-R.T)
if theta < 1e-7:
return skew/2
if np.pi-theta < 1e-4:
_, vectors = np.linalg.eigh((R+R.T)/2)
axis = vectors[:, -1]
if axis @ skew < 0:
axis = -axis
return theta*axis
return theta*skew/(2*np.sin(theta))
def euler_zyx(yaw, pitch, roll):
z, y, x = hat([0,0,yaw]), hat([0,pitch,0]), hat([roll,0,0])
return so3_exp(vee(z)) @ so3_exp(vee(y)) @ so3_exp(vee(x))
def to_euler_zyx(R):
pitch = np.arcsin(np.clip(-R[2,0], -1, 1))
if abs(np.cos(pitch)) < 1e-7:
return np.array([np.arctan2(-R[0,1], R[1,1]), pitch, 0.])
return np.array([np.arctan2(R[1,0],R[0,0]), pitch, np.arctan2(R[2,1],R[2,2])])
def quat_from_R(R):
v = so3_log(R)
theta = np.linalg.norm(v)
if theta < 1e-8:
return np.r_[1-theta**2/8, (0.5-theta**2/48)*v]
return np.r_[np.cos(theta/2), np.sin(theta/2)*v/theta]
def R_from_quat(q):
q = np.asarray(q, dtype=float)
if np.linalg.norm(q) == 0:
raise ValueError('Cuaternión nulo')
w, x, y, z = q / np.linalg.norm(q)
u = np.array([x,y,z])
return (w*w-u@u)*np.eye(3) + 2*np.outer(u,u) + 2*w*hat(u)
def distance(A, B):
return np.linalg.norm(so3_log(A.T@B))
def slerp(q0, q1, t):
q0 = np.array(q0, dtype=float, copy=True)
q1 = np.array(q1, dtype=float, copy=True)
if np.linalg.norm(q0) == 0 or np.linalg.norm(q1) == 0:
raise ValueError('Cuaternión nulo')
q0 /= np.linalg.norm(q0); q1 /= np.linalg.norm(q1)
c = np.clip(q0@q1, -1, 1)
if c < 0:
q1, c = -q1, -c
if c > 0.9995:
q = (1-t)*q0+t*q1
return q/np.linalg.norm(q)
omega = np.arccos(c)
return (np.sin((1-t)*omega)*q0+np.sin(t*omega)*q1)/np.sin(omega)Compare two thousand rotations generated by SciPy. Distance is calculated between matrices, not axis-angle vectors: at the axis sign can vary without changing the rotation. The test also includes cases near zero and and checks Euler reconstruction, including when its representation is not unique.
samples = Rotation.random(2000, random_state=13).as_matrix()
max_exp, max_quat, max_euler = 0., 0., 0.
for R in samples:
max_exp = max(max_exp, np.max(np.abs(so3_exp(so3_log(R))-R)))
max_quat = max(max_quat, np.max(np.abs(R_from_quat(quat_from_R(R))-R)))
max_euler = max(max_euler, np.max(np.abs(euler_zyx(*to_euler_zyx(R))-R)))
for angle in [1e-9, np.deg2rad(179.999), np.pi]:
R = Rotation.from_rotvec(np.array([1.,2.,3.])/np.sqrt(14)*angle).as_matrix()
assert np.allclose(so3_exp(so3_log(R)), R, atol=1e-7)
assert np.allclose(R_from_quat(quat_from_R(R)), R, atol=1e-7)
for pitch in [-np.pi/2, np.pi/2]:
R = euler_zyx(0.7, pitch, -0.2)
assert np.allclose(euler_zyx(*to_euler_zyx(R)), R, atol=1e-7)
angles = np.array([0.7, -0.4, 0.2])
assert np.allclose(euler_zyx(*angles), Rotation.from_euler('ZYX', angles).as_matrix())
from scipy.spatial.transform import Slerp
for i in range(0, 60, 2):
q0, q1 = quat_from_R(samples[i]), quat_from_R(samples[i+1])
scipy_path = Slerp([0,1], Rotation.from_matrix(samples[i:i+2]))
for t in [0., 0.25, 0.5, 1.]:
assert np.allclose(R_from_quat(slerp(q0,q1,t)), scipy_path([t]).as_matrix()[0], atol=1e-7)
assert np.allclose(R_from_quat(slerp(q0,-q0,0.5)), samples[i], atol=1e-7)
print('Máximo error exponencial/log:', max_exp)
print('Máximo error cuaternión:', max_quat)
print('Máximo error Euler:', max_euler)
assert max(max_exp, max_quat, max_euler) < 1e-6Averaging orientations
The element-wise mean of matrices need not be orthogonal. You can project it onto using SVD, adjusting the determinant sign. Another possibility is to construct : its principal eigenvector does not change when any is replaced by . A Karcher mean minimizes the sum of squared geodesic distances; near a solution, it averages relative logarithms in the tangent space and updates by multiplying by the exponential. Widely dispersed data can have non-unique minima: the iteration in this lab does not guarantee the global minimum.
rng = np.random.default_rng(10)
truth = so3_exp(np.array([0.4, -0.3, 0.2]))
Rs = np.array([truth @ so3_exp(v) for v in rng.normal(0, 0.15, (80, 3))])
naive = Rs.mean(axis=0)
U, _, Vt = np.linalg.svd(naive)
D = np.diag([1., 1., np.linalg.det(U@Vt)])
projected = U@D@Vt
qs = np.array([quat_from_R(R) for R in Rs])
_, vectors = np.linalg.eigh(qs.T@qs)
quat_mean = R_from_quat(vectors[:,-1])
karcher = projected.copy()
for _ in range(30):
update = np.mean([so3_log(karcher.T@R) for R in Rs], axis=0)
karcher = karcher @ so3_exp(update)
if np.linalg.norm(update) < 1e-10:
break
print('Error de ortogonalidad media ingenua:', np.linalg.norm(naive.T@naive-np.eye(3)))
print('Errores geodésicos (proyectada, cuaterniones, Karcher):',
np.round([distance(truth, projected), distance(truth, quat_mean), distance(truth, karcher)], 6))This is a synthetic run of a perturbation model, not a robot measurement. Its result changes with the seed and dispersion. A single run does not establish that one method always wins.
To examine the criterion, calculate the sum of squared values at each iteration. The local stationary condition is that the mean relative logarithm is zero, provided consistent branches are chosen and the solution is away from the discontinuity at . The eigenvector quaternion mean optimizes a different criterion related to squared inner products, so it need not exactly match the intrinsic mean. SVD projection minimizes a matrix distance, also different from geodesic distance.
Library conventions
SciPy returns by default and accepts scalar_first=True; MuJoCo uses . Eigen accepts in the four-scalar constructor, but stores coeffs() as . Also check whether an API rotates a vector or transforms its coordinates between frames. When integrating quaternions numerically, renormalize and check the method: unit norm is a constraint, not a property that an arbitrary integrator preserves exactly.
Exercises
Step 1 of 2. Which identity gives the third power?
Step 1 of 2. What is the matrix in an orthonormal basis aligned with the axis?
so3_log(R) for a valid rotation matrix, returning the principal vector. Handle angles near zero and pi.def so3_log(R):
pass