Module contents
Lesson 2 of 33Core 110 min

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: v′=Rv\vb{v}'=\mat{R}\vb{v}. To change coordinates between frames using the inverse operation, use R⊤\mat{R}\T.

The identity belongs to the set. If A\mat{A} and B\mat{B} belong to it, (AB)⊤(AB)=I(\mat{A}\mat{B})\T(\mat{A}\mat{B})=\mat{I} and det⁡(AB)=1\det(\mat{A}\mat{B})=1. The inverse is R⊤\mat{R}\T, 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 R2R1\mat{R}_2\mat{R}_1 applies R1\mat{R}_1 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 π\pi 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 R=Rz(ψ)Ry(θ)Rx(ϕ)\mat{R}=\mat{R}_z(\psi)\mat{R}_y(\theta)\mat{R}_x(\phi): roll ϕ\phi, pitch θ\theta, yaw ψ\psi. With active column vectors the rotation about fixed xx is applied first, then fixed yy, and finally fixed zz; the equivalent interpretation uses moving axes in reverse order. The letters ZYX alone do not unambiguously specify every convention used by a library.

InteractiveThree axes, but not always three directions
  • Yaw
  • Pitch
  • Roll
  • Body vector
20
30
25
Axis separation: |cos pitch|0.866
Jacobian rank3
Move pitch to 90°. The rings and arrows show the instantaneous yaw, pitch and roll axes. The magenta arrow is a body vector.

In world coordinates the columns of the angular-velocity Jacobian with respect to (ψ˙,θ˙,ϕ˙)(\dot\psi,\dot\theta,\dot\phi) are ez\vb{e}_z, Rz(ψ)ey\mat{R}_z(\psi)\vb{e}_y and Rz(ψ)Ry(θ)ex\mat{R}_z(\psi)\mat{R}_y(\theta)\vb{e}_x. Its determinant has absolute value ∣cos⁡θ∣|\cos\theta|. At θ=π/2\theta=\pi/2 the third axis is −ez-\vb{e}_z: 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 SO(3)SO(3) is invertible.

To reconstruct the angles away from the singularity, the entry R31=−sin⁡θR_{31}=-\sin\theta gives θ=arcsin⁡(−R31)\theta=\arcsin(-R_{31}) on the branch [−π/2,π/2][-\pi/2,\pi/2]. The pairs (R21,R11)(R_{21},R_{11}) and (R32,R33)(R_{32},R_{33}) give yaw and roll respectively using atan2. When cos⁡θ=0\cos\theta=0, 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 v∈R3\vb{v}\in\R^3, define [v]×[\vb{v}]_\times as the skew-symmetric matrix satisfying [v]×x=v×x[\vb{v}]_\times\vb{x}=\vb{v}\times\vb{x}. The exponential map of SO(3) sends ω=θn\vb{\omega}=\theta\vb{n} to exp⁡([ω]×)\exp([\vb{\omega}]_\times), with ∥n∥=1\norm{\vb{n}}=1. The set of skew-symmetric matrices is the algebra so(3)\mathfrak{so}(3).

This is the same matrix exponential that solves the linear system of differential equations v˙=[ω]×v\dot{\vb{v}}=[\vb{\omega}]_\times\vb{v} for constant angular velocity. In the plane perpendicular to the axis, the complex eigenvalues e±iθe^{\pm i\theta} correspond to planar rotation.

Rodrigues’ axis-angle formula is

R=I+sin⁡θ[n]×+(1−cos⁡θ)[n]×2.\mat{R}=\mat{I}+\sin\theta[\vb{n}]_\times+(1-\cos\theta)[\vb{n}]_\times^2.

To derive it, write N=[n]×\mat{N}=[\vb{n}]_\times. The vector triple-product identity gives N2=nn⊤−I\mat{N}^2=\vb{n}\vb{n}\T-\mat{I} and hence N3=−N\mat{N}^3=-\mat{N}. In the series for exp⁡(θN)\exp(\theta\mat{N}), odd powers sum to sin⁡θ N\sin\theta\,\mat{N} and nonconstant even powers sum to (1−cos⁡θ)N2(1-\cos\theta)\mat{N}^2. Applied to v\vb{v}, the formula produces the terms vcos⁡θ\vb{v}\cos\theta, (n×v)sin⁡θ(\vb{n}\times\vb{v})\sin\theta and n(n⊤v)(1−cos⁡θ)\vb{n}(\vb{n}\T\vb{v})(1-\cos\theta).

InteractiveThree terms for a rotation
  • Axis
  • First term
  • Second
  • Third
  • Result
30
45
70
Parallel component0.97
Rotated norm1.12
Vary the axis and angle. The orange, aquamarine and yellow arrows add head to tail; magenta is the result. The circle is the exact orbit of a fixed vector.

The principal logarithm returns θn\theta\vb{n} with θ∈[0,π]\theta\in[0,\pi]. For 0<θ<π0<\theta<\pi, θ=arccos⁡((tr⁡R−1)/2)\theta=\arccos((\tr\mat{R}-1)/2) and θn=θ vee⁡(R−R⊤)/(2sin⁡θ)\theta\vb{n}=\theta\,\operatorname{vee}(\mat{R}-\mat{R}\T)/(2\sin\theta). Near zero use the local expansion; near π\pi division by sin⁡θ\sin\theta is unstable, so obtain the axis from the symmetric part. At π\pi both axis signs describe the same rotation, so the logarithm is not unique. Clip the arccos argument to [−1,1][-1,1] to tolerate rounding.

The skew-symmetric relation follows by subtracting the transpose of Rodrigues’ formula: R−R⊤=2sin⁡θ[n]×\mat{R}-\mat{R}\T=2\sin\theta[\vb{n}]_\times. Near zero, the ratio θ/sin⁡θ\theta/\sin\theta tends to one, leaving approximately vee⁡(R−R⊤)/2\operatorname{vee}(\mat{R}-\mat{R}\T)/2. Near π\pi, 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 π\pi, the sign of the skew-symmetric part orients that eigenvector; exactly at π\pi either sign is valid.

The exponential map is not ordinary addition of orientations: in general exp⁡([a]×)exp⁡([b]×)≠exp⁡([a+b]×)\exp([\vb{a}]_\times)\exp([\vb{b}]_\times)\ne\exp([\vb{a}+\vb{b}]_\times). 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 q=(w,u)q=(w,\vb{u}), with w2+∥u∥2=1w^2+\norm{\vb{u}}^2=1. Rotation about unit axis n\vb{n} by angle θ\theta corresponds to (cos⁡(θ/2),nsin⁡(θ/2))(\cos(\theta/2),\vb{n}\sin(\theta/2)). The Hamilton product is

(w,u)(s,v)=(ws−u⊤v,  wv+su+u×v).(w,\vb{u})(s,\vb{v})=(ws-\vb{u}\T\vb{v},\;w\vb{v}+s\vb{u}+\vb{u}\times\vb{v}).

The conjugate is q∗=(w,−u)q^*=(w,-\vb{u}) and for unit quaternions q−1=q∗q^{-1}=q^*. The rotated vector is the vector part of q(0,v)q∗q(0,\vb{v})q^*. Both qq and −q-q give the same result: this is double coverage. After a 360° turn the body returns to its orientation, but the continuous representative moves from qq to −q-q; returning to the initial quaternion takes 720°.

To see why the action does not distinguish signs, replace qq by −q-q: two minus signs appear, one on either side of (0,v)(0,\vb{v}), and cancel. Composition preserves the order of actions: applying q1q_1 and then q2q_2 is equivalent to the product q2q1q_2q_1. 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 q=(w,u)q=(w,\vb{u}) is (w2−u⊤u)I+2uu⊤+2w[u]×(w^2-\vb{u}\T\vb{u})\mat{I}+2\vb{u}\vb{u}\T+2w[\vb{u}]_\times. Substituting w=cos⁡(θ/2)w=\cos(\theta/2) and u=nsin⁡(θ/2)\vb{u}=\vb{n}\sin(\theta/2) recovers Rodrigues’ formula via double-angle identities. The formula also reveals the units: qq 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.

InteractiveOne body turn, half a quaternion turn
  • Without sign correction
  • With correction
240
Scalar component w−0.50
Component z0.87
Corrected arc (degrees)−120.0
The (w,z)(w,z) circle is a section of the unit quaternion sphere. Compare the interpolation arc with and without choosing the representative in the nearest hemisphere.

The geodesic distance between rotations is the principal angle of R1⊤R2\mat{R}_1\T\mat{R}_2, in [0,π][0,\pi]. Since a rotation fixes its axis and turns the perpendicular plane, its trace is 1+2cos⁡θ1+2\cos\theta. Therefore d=arccos⁡(clip⁡((tr⁡(R1⊤R2)−1)/2,−1,1))d=\arccos(\operatorname{clip}((\tr(\mat{R}_1\T\mat{R}_2)-1)/2,-1,1)). For unit quaternions it is also 2arccos⁡(∣q1⊤q2∣)2\arccos(|q_1\T q_2|), with the product clipped to [0,1][0,1].

Spherical interpolation, or slerp, between unit representatives uses q(t)=sin⁡((1−t)Ω)q0/sin⁡Ω+sin⁡(tΩ)q1/sin⁡Ωq(t)=\sin((1-t)\Omega)q_0/\sin\Omega+\sin(t\Omega)q_1/\sin\Omega, where Ω=arccos⁡(q0⊤q1)\Omega=\arccos(q_0\T q_1). If the product is negative, replace q1q_1 by −q1-q_1 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 tt advances uniformly. For a 180° difference in SO(3)SO(3) 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 Q\mat{Q} on the left, (QR1)⊤(QR2)=R1⊤R2(\mat{Q}\mat{R}_1)\T(\mat{Q}\mat{R}_2)=\mat{R}_1\T\mat{R}_2, 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 π\pi it uses the eigenvector of the symmetric part with the largest eigenvalue and orients its sign using the skew-symmetric part when possible.

[ ]Rotations from scratchBrowser
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 π\pi the axis sign can vary without changing the rotation. The test also includes cases near zero and π\pi and checks Euler reconstruction, including when its representation is not unique.

[ ]Validate against SciPyBrowser
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-6

Averaging orientations

The element-wise mean of matrices need not be orthogonal. You can project it onto SO(3)SO(3) using SVD, adjusting the determinant sign. Another possibility is to construct ∑iqiqi⊤\sum_i q_iq_i\T: its principal eigenvector does not change when any qiq_i is replaced by −qi-q_i. 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.

[ ]Averaging noisy orientationsBrowser
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 d(R,Ri)d(\mat{R},\mat{R}_i) 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 π\pi. 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 (x,y,z,w)(x,y,z,w) by default and accepts scalar_first=True; MuJoCo uses (w,x,y,z)(w,x,y,z). Eigen accepts (w,x,y,z)(w,x,y,z) in the four-scalar constructor, but stores coeffs() as (x,y,z,w)(x,y,z,w). 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

Numeric
Given q1 = (1, 0, 0, 0) and q2 = (cos 30°, sin 30°, 0, 0), what is the relative angle in degrees?
Quiz
Which loss handles the double coverage of two unit quaternions correctly?
Proof
Prove: The exponential of a unit-axis cross-product matrix is Rodrigues' formula.
0
Let N = [n]× with n of unit norm.

Step 1 of 2. Which identity gives the third power?

Proof
Prove: The trace of a rotation through angle θ is 1 + 2 cos θ.
0
The axis remains fixed and the perpendicular plane rotates through angle θ.

Step 1 of 2. What is the matrix in an orthonormal basis aligned with the axis?

Code
Implement so3_log(R) for a valid rotation matrix, returning the principal vector. Handle angles near zero and pi.
def so3_log(R):
  pass
Shift+Enter to run
Key idea
An orientation belongs to SO(3), not an arbitrary list of parameters: choose an explicit convention and respect singularities, signs and geometry in calculations.