Why rotations are the hard part
In Frames and rigid transforms the rotation block of a pose was a matrix described by one angle. Angles in the plane add, commute and interpolate without fuss. In three dimensions every one of those comforts goes away.
Hold a book flat in front of you, spine to the left. Turn it 90° about a vertical axis, then 90° about the axis pointing at you. Now start again and do the same two turns in the opposite order. The book ends up in two different orientations. Order matters, as it did for transforms, but now it matters even for rotations alone.
A drone's flight controller updates its estimate of its own orientation a thousand times a second from a gyroscope. A robot arm must turn its gripper smoothly from "pointing down" to "pointing at the shelf". A camera's orientation must be stored in a file, sent over a network, averaged across measurements and optimised in SLAM. Each of these jobs is easier in a different representation, and each representation has a trap: Euler angles have gimbal lock, matrices drift away from being rotations, axis–angle is ambiguous near 180°, and quaternions come with two multiplication conventions, two storage orders and two signs for every rotation. This lesson walks through all of them, measures their failures in NumPy, and ends with a table of which to use when.
Rotation matrices and SO(3)
Definition— SO(3)
A rotation matrix is a real matrix with and . The set of all of them, with matrix multiplication, is the special orthogonal group . As in the plane, the columns of are the axes of frame B written in frame A, and .
The rotations about the coordinate axes are the building blocks:
Each leaves its own axis fixed and turns the other two by the right-hand rule: with your right thumb along the axis, your fingers curl in the positive direction. (The minus sign in sits below the diagonal, not above it; that is the right-hand rule, not a typo, because .)
Theorem— Euler's rotation theorem
Every leaves some line through the origin fixed: there is a unit vector with . So every rotation is a rotation by some angle about some axis.
Proof
We show that 1 is an eigenvalue of , that is, . Using and : . A number equal to its own negative is zero. The odd dimension is essential: in the plane the same argument gives nothing, and indeed a 2-D rotation fixes only the origin.
∎
Nine entries, six constraints ( is a symmetric equation), three degrees of freedom: so we expect three numbers to suffice. They do, locally, but as you will see no choice of three numbers works everywhere without a flaw.
Euler angles and gimbal lock
The most familiar three numbers are Euler angles: describe a rotation as three successive rotations about coordinate axes. Robotics and aviation mostly use roll, pitch and yaw ():
Read right to left, this rolls about the fixed axis, then pitches about the fixed axis, then yaws about the fixed axis. Read left to right, it yaws about the body's , then pitches about the body's new , then rolls about the body's newest . Both readings describe the same matrix: right-multiplication applies a rotation in the moving body frame, exactly as in the last lesson. This "" convention is the one ROS and URDF use for their rpy values.
There are twelve axis sequences in use (, , , and so on), each of which can be read with fixed or moving axes. Aerospace and ROS share the yaw–pitch–roll sequence above, the classical mechanics of spinning tops favours , and graphics and animation tools offer several. Whenever you read Euler angles, find out which sequence they mean.
The code below builds roll–pitch–yaw matrices, recovers the angles, shows two rotations failing to commute, and then looks for trouble at pitch .
import numpy as np
def Rx(a):
c, s = np.cos(a), np.sin(a)
return np.array([[1, 0, 0], [0, c, -s], [0, s, c]])
def Ry(a):
c, s = np.cos(a), np.sin(a)
return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
def Rz(a):
c, s = np.cos(a), np.sin(a)
return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
def rpy_to_matrix(roll, pitch, yaw):
"""Roll about x, then pitch about y, then yaw about z, all about the fixed axes."""
return Rz(yaw) @ Ry(pitch) @ Rx(roll)
def matrix_to_rpy(R):
pitch = np.arcsin(np.clip(-R[2, 0], -1.0, 1.0))
roll = np.arctan2(R[2, 1], R[2, 2])
yaw = np.arctan2(R[1, 0], R[0, 0])
return roll, pitch, yaw
d = np.radians
A, B = Rx(d(90)), Rz(d(90))
print("Rx(90) Rz(90) sends the x axis to", (A @ B @ [1, 0, 0]).round(3))
print("Rz(90) Rx(90) sends the x axis to", (B @ A @ [1, 0, 0]).round(3))
R = rpy_to_matrix(d(10), d(-20), d(135))
print("round trip (deg):", np.degrees(matrix_to_rpy(R)).round(6))
# Gimbal lock: at pitch = 90 degrees, roll and yaw stop being independent.
R1 = rpy_to_matrix(d(30), d(90), d(50))
R2 = rpy_to_matrix(d(10), d(90), d(30))
print("(30, 90, 50) and (10, 90, 30) give the same matrix:", np.allclose(R1, R2))
def jacobian(roll, pitch, yaw, h=1e-6):
"""How the 9 entries of R change with each angle: a 9 x 3 matrix, by central differences."""
cols = []
for k in range(3):
e = np.zeros(3)
e[k] = h
a, b = np.array([roll, pitch, yaw]) + e, np.array([roll, pitch, yaw]) - e
cols.append((rpy_to_matrix(*a) - rpy_to_matrix(*b)).ravel() / (2 * h))
return np.array(cols).T
print("pitch (deg) singular values of dR/d(roll, pitch, yaw)")
for p in [0, 45, 80, 89, 89.9, 90]:
sv = np.linalg.svd(jacobian(d(20), d(p), d(40)), compute_uv=False)
print(f"{p:10} {sv.round(4)}")The book experiment, in numbers: the same two 90° turns send the body's axis to in one order and to in the other.
Then the trouble. At pitch the angles and give the same matrix: only the difference between yaw and roll matters, because pitching by has swung the body's axis onto the world's vertical, so roll and yaw now turn about the same line. One degree of freedom has vanished from the parameterisation. That is gimbal lock.
The last table measures it. The matrix of derivatives of with respect to the three angles tells you how far the rotation moves when each angle moves. Away from the singularity it has three healthy singular values. As pitch approaches the smallest falls to at , at and exactly zero at : some direction of rotation can no longer be reached by small changes of the angles, and near there, small changes of orientation demand huge changes of roll and yaw. A controller or estimator working in Euler angles sees this as angle rates exploding.
Euler angles are excellent for humans (a pilot or an operator understands "pitch up 5°"), for configuration files, and for vehicles that never approach the singularity, such as cars. They are a poor choice for anything that integrates, interpolates or optimises over all orientations.
Axis–angle and Rodrigues' formula
Euler's theorem suggests a more geometric description: a unit axis and an angle . Packing them into one vector gives the rotation vector , three numbers, which is also what a gyroscope measures per unit time.
Definition— Skew-symmetric matrix
For , let , so that for every .
Theorem— Rodrigues' formula
The rotation by angle about the unit axis is
Proof
Split any vector into a part along the axis and a part perpendicular to it: with . The rotation leaves alone and turns by within the plane perpendicular to . That plane has the perpendicular pair and (the latter is turned by , with the same length), so the rotated vector is
Now , so and . Substituting gives for every .
∎
Going back, from a matrix to axis and angle (the matrix logarithm), uses two facts you can check from the formula: , and . So and the axis can be read from the off-diagonal entries of , divided by . That division fails at (any axis will do, which is harmless) and at (where and the axis must be found another way, for example from ). Robust code treats both cases separately.
The map from rotation vectors to matrices, , is the exponential map of the Lie group : Rodrigues' formula is exactly , summed in closed form. Lumenary Math's Lie groups and Lie algebras develops this; for us it means that small rotations behave like vectors (they can be added, scaled and averaged), which is why estimators and optimisers express corrections to an orientation as rotation vectors.
Unit quaternions
In 1843 William Rowan Hamilton was looking for a way to multiply triples of numbers, as complex numbers multiply pairs. He found that it works with four: a quaternion is with
from which , , and so on: multiplication does not commute, which is just what rotations need. Writing with a scalar part and a vector part , the product is
The conjugate is , and , so a unit quaternion () has inverse .
Definition— Rotation quaternion
The rotation by angle about the unit axis is represented by the unit quaternion
It rotates a vector by the "sandwich" , and the rotation corresponds to the product . Both and represent the same rotation.
Expanding the sandwich with the product rule gives back Rodrigues' formula, the half-angles turning into whole angles through and . The sign ambiguity comes from the half-angle too: and are the same rotation, but changes sign between them.
Note
Conventions, again. This course uses Hamilton's quaternions, with and , and writes them , scalar first. Many libraries store them scalar-last: ROS messages (geometry_msgs/Quaternion has fields x, y, z, w), tf2's Quaternion(x, y, z, w) constructor, and SciPy's Rotation by default. Eigen's constructor takes (w, x, y, z) but stores (x, y, z, w) internally; MuJoCo uses (w, x, y, z). Some aerospace and visual-inertial navigation code uses the JPL convention, in which the product is defined the other way round. When orientations look wrong, check storage order and convention before anything else.
Quaternions and conversions in NumPy
The program implements Rodrigues' formula, the logarithm, the quaternion product, rotation of a vector, and conversions in both directions, then checks them against each other on a known rotation and on a thousand random ones (random unit quaternions are easy to make: normalise four independent normal samples).
import numpy as np
def skew(v):
"""The matrix [v] with [v] @ u == np.cross(v, u)."""
x, y, z = v
return np.array([[0, -z, y], [z, 0, -x], [-y, x, 0]])
def rodrigues(axis, angle):
k = np.asarray(axis, float) / np.linalg.norm(axis)
K = skew(k)
return np.eye(3) + np.sin(angle) * K + (1 - np.cos(angle)) * K @ K
def log_so3(R):
"""Axis and angle of a rotation matrix (for angles away from 0 and 180 degrees)."""
angle = np.arccos(np.clip((np.trace(R) - 1) / 2, -1.0, 1.0))
axis = np.array([R[2, 1] - R[1, 2], R[0, 2] - R[2, 0], R[1, 0] - R[0, 1]]) / (2 * np.sin(angle))
return axis, angle
# Quaternions in Hamilton's convention, stored here as (w, x, y, z).
def quat_from_axis_angle(axis, angle):
k = np.asarray(axis, float) / np.linalg.norm(axis)
return np.concatenate([[np.cos(angle / 2)], np.sin(angle / 2) * k])
def qmul(p, q):
"""Hamilton product p q."""
pw, pv, qw, qv = p[0], p[1:], q[0], q[1:]
return np.concatenate([[pw * qw - pv @ qv], pw * qv + qw * pv + np.cross(pv, qv)])
def qconj(q):
return np.array([q[0], -q[1], -q[2], -q[3]])
def qrotate(q, v):
"""Rotate the 3-vector v by the unit quaternion q: q (0, v) q*."""
return qmul(qmul(q, np.concatenate([[0.0], v])), qconj(q))[1:]
def quat_to_matrix(q):
w, x, y, z = q
return np.array([
[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
[2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
[2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]])
def matrix_to_quat(R):
"""Robust conversion: pick the largest of 4w^2, 4x^2, 4y^2, 4z^2 to divide by."""
t = np.trace(R)
cands = [t, R[0, 0], R[1, 1], R[2, 2]]
i = int(np.argmax(cands))
if i == 0:
s = 2 * np.sqrt(1 + t)
q = [s / 4, (R[2, 1] - R[1, 2]) / s, (R[0, 2] - R[2, 0]) / s, (R[1, 0] - R[0, 1]) / s]
elif i == 1:
s = 2 * np.sqrt(1 + R[0, 0] - R[1, 1] - R[2, 2])
q = [(R[2, 1] - R[1, 2]) / s, s / 4, (R[0, 1] + R[1, 0]) / s, (R[0, 2] + R[2, 0]) / s]
elif i == 2:
s = 2 * np.sqrt(1 + R[1, 1] - R[0, 0] - R[2, 2])
q = [(R[0, 2] - R[2, 0]) / s, (R[0, 1] + R[1, 0]) / s, s / 4, (R[1, 2] + R[2, 1]) / s]
else:
s = 2 * np.sqrt(1 + R[2, 2] - R[0, 0] - R[1, 1])
q = [(R[1, 0] - R[0, 1]) / s, (R[0, 2] + R[2, 0]) / s, (R[1, 2] + R[2, 1]) / s, s / 4]
q = np.array(q)
return q if q[0] >= 0 else -q # choose the representative with w >= 0
def show(a):
return np.round(a, 6) + 0.0 # + 0.0 turns -0.0 into 0.0 for printing
axis, angle = [1, 1, 1], np.radians(120)
R = rodrigues(axis, angle)
q = quat_from_axis_angle(axis, angle)
print("R(120 deg about (1,1,1)) =\n", show(R))
print("q =", show(q), " |q| =", round(float(np.linalg.norm(q)), 12))
v = np.array([1.0, 0.0, 0.0])
print("R v =", show(R @ v), " q v q* =", show(qrotate(q, v)))
print("quat_to_matrix(q) == R:", np.allclose(quat_to_matrix(q), R), " and for -q:", np.allclose(quat_to_matrix(-q), R))
k, a = log_so3(R)
print("log: axis", show(k / np.linalg.norm(k)), "angle", round(float(np.degrees(a)), 6))
rng = np.random.default_rng(7)
worst = 0.0
for _ in range(1000):
q1, q2 = rng.normal(size=4), rng.normal(size=4)
q1, q2 = q1 / np.linalg.norm(q1), q2 / np.linalg.norm(q2)
worst = max(worst,
np.abs(quat_to_matrix(qmul(q1, q2)) - quat_to_matrix(q1) @ quat_to_matrix(q2)).max(),
min(np.abs(matrix_to_quat(quat_to_matrix(q1)) - q1).max(),
np.abs(matrix_to_quat(quat_to_matrix(q1)) + q1).max()))
print("1000 random checks of q1 q2 <-> R1 R2 and matrix -> quaternion: worst error", f"{worst:.1e}")The rotation by about is a tidy example: it permutes the axes, , so its matrix is a permutation matrix, and its quaternion is . The matrix and the quaternion sandwich agree on where goes, and give the same matrix, and on a thousand random pairs the product of quaternions matches the product of matrices to about , which is rounding error.
The matrix-to-quaternion function deserves a word. The obvious formula, and then divide the off-diagonal differences by , loses accuracy badly when is near zero (rotations near ). The robust version, usually credited to Shepperd (1978), first finds which of is largest and divides by that one.
Interpolation: slerp against lerp
A robot arm should turn its gripper from orientation to orientation at a steady rate; an animation, a camera path, a trajectory generator all need the in-between orientations. With quaternions the natural answer is spherical linear interpolation (slerp), introduced to computer graphics by Ken Shoemake in 1985: move along the great circle from to on the unit sphere at constant speed,
is the angle between and as 4-D vectors, half of the rotation angle between the two orientations. Two details matter in practice. If , replace by first, or the interpolation goes the long way round. And if is very close to 1, is nearly zero; fall back to the simpler formula below.
The tempting alternatives are lerp, , which is not even a unit quaternion in between, and nlerp, lerp divided by its length, which is a valid rotation but moves at a varying speed. The code measures all three for a turn of , and then tries averaging rotation matrices directly.
import numpy as np
def quat_from_axis_angle(axis, angle):
k = np.asarray(axis, float) / np.linalg.norm(axis)
return np.concatenate([[np.cos(angle / 2)], np.sin(angle / 2) * k])
def angle_between(p, q):
"""Rotation angle (degrees) taking unit quaternion p to unit quaternion q."""
return np.degrees(2 * np.arccos(np.clip(abs(p @ q), -1.0, 1.0)))
def slerp(p, q, t):
d = p @ q
if d < 0: # q and -q are the same rotation: take the short way round
q, d = -q, -d
if d > 0.9995: # nearly identical: fall back to normalised lerp
r = p + t * (q - p)
return r / np.linalg.norm(r)
theta = np.arccos(d) # angle between p and q on the 4-D unit sphere
return (np.sin((1 - t) * theta) * p + np.sin(t * theta) * q) / np.sin(theta)
def lerp(p, q, t):
return (1 - t) * p + t * q
def nlerp(p, q, t):
r = lerp(p, q, t)
return r / np.linalg.norm(r)
p = quat_from_axis_angle([0, 0, 1], 0.0)
q = quat_from_axis_angle([1, 2, 2], np.radians(170))
print(" t slerp angle nlerp angle |lerp|")
for t in [0, 0.25, 0.5, 0.75, 1]:
print(f"{t:4} {angle_between(p, slerp(p, q, t)):9.2f} {angle_between(p, nlerp(p, q, t)):11.2f} {np.linalg.norm(lerp(p, q, t)):6.3f}")
ts = np.linspace(0, 1, 21)
for name, f in [("slerp", slerp), ("nlerp", nlerp)]:
path = [f(p, q, t) for t in ts]
steps = [angle_between(a, b) for a, b in zip(path, path[1:])]
print(f"{name}: 20 equal time steps turn between {min(steps):.2f} and {max(steps):.2f} degrees")
# Interpolating rotation *matrices* entry by entry is worse: the halfway matrix is not a rotation.
def quat_to_matrix(q):
w, x, y, z = q
return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
[2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
[2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]])
M = 0.5 * quat_to_matrix(p) + 0.5 * quat_to_matrix(q)
print("halfway matrix: det =", round(float(np.linalg.det(M)), 4), " largest error in M^T M - I =", round(float(np.abs(M.T @ M - np.eye(3)).max()), 4))Slerp's angles go up in exact steps of , and twenty equal time steps each turn exactly . Nlerp agrees at the endpoints and at the middle (by symmetry) but reaches only at , and its steps range from to : the gripper would speed up through the middle of the motion by a factor of 1.75. Plain lerp's halfway quaternion has length , so it is not a rotation at all until normalised. Averaging the two matrices is worse still: the result has determinant and is nowhere near orthogonal; it squashes space almost flat.
Numerical drift and re-normalisation
An IMU-based orientation estimator integrates the gyroscope: every millisecond it composes the current orientation with a tiny rotation . Each multiplication rounds, and the result slowly stops being a rotation. The program integrates a constant rotation rate at 1 kHz for 20 seconds, in 32-bit floats (common on microcontrollers; Lumenary CS's Representing data explains floating point) and 64-bit floats, both as a matrix and as a quaternion, and then repairs the 32-bit results.
import numpy as np
def rodrigues(w_dt):
"""Rotation matrix for the small rotation vector w_dt (axis times angle)."""
a = np.linalg.norm(w_dt)
x, y, z = w_dt / a
K = np.array([[0, -z, y], [z, 0, -x], [-y, x, 0]])
return np.eye(3) + np.sin(a) * K + (1 - np.cos(a)) * K @ K
def qmul(p, q):
pw, pv, qw, qv = p[0], p[1:], q[0], q[1:]
out = np.empty(4, dtype=p.dtype)
out[0] = pw * qw - pv @ qv
out[1:] = pw * qv + qw * pv + np.cross(pv, qv)
return out
omega = np.array([0.3, -0.2, 0.5]) # a gyroscope reading in rad/s, held constant
dt = 0.001 # a 1 kHz update loop
w_dt = omega * dt
a = np.linalg.norm(w_dt)
final = {}
for dtype in (np.float32, np.float64):
dR = rodrigues(w_dt).astype(dtype)
dq = np.concatenate([[np.cos(a / 2)], np.sin(a / 2) * w_dt / a]).astype(dtype)
R, q = np.eye(3, dtype=dtype), np.array([1, 0, 0, 0], dtype=dtype)
print(f"{np.dtype(dtype).name}: steps max|R^T R - I| |q| - 1")
for step in range(1, 20001):
R = R @ dR # body-frame increments compose on the right
q = qmul(q, dq)
if step in (100, 1000, 5000, 20000):
orth = np.abs(R.T @ R - np.eye(3)).max()
print(f" {step:6} {orth:11.2e} {float(np.linalg.norm(q)) - 1:9.2e}")
final[np.dtype(dtype).name] = (R, q)
def nearest_rotation(M):
"""The rotation matrix closest to M, from its singular value decomposition."""
U, _, Vt = np.linalg.svd(M)
D = np.diag([1.0, 1.0, np.linalg.det(U @ Vt)])
return U @ D @ Vt
R32, q32 = final["float32"]
R_fixed = nearest_rotation(R32.astype(np.float64))
q_fixed = q32.astype(np.float64) / np.linalg.norm(q32.astype(np.float64))
print("float32 R after re-orthonormalising: max|R^T R - I| =", f"{np.abs(R_fixed.T @ R_fixed - np.eye(3)).max():.1e}")
print("float32 q after dividing by |q|: |q| - 1 =", f"{np.linalg.norm(q_fixed) - 1:.1e}")In 64-bit arithmetic the matrix stays orthogonal to about after 20,000 steps, and nobody need worry. In 32-bit arithmetic, after 20 seconds, the matrix's columns are off by and the quaternion's length has shrunk by . The errors do not cancel like a random walk: they drift steadily, partly because the increment itself, rounded to 32 bits, is about one part in too short, and that shortfall compounds at every step. Left alone for an hour of flight, such a matrix would scale and shear every vector it touches.
The repairs are cheap. A quaternion is re-normalised by dividing by its length, four multiplications and a square root. A matrix is replaced by the nearest rotation matrix, computed from its singular value decomposition as (with a sign fix if the determinant would be ), or more cheaply by re-orthogonalising its columns with Gram–Schmidt. Real estimators do this every step or every few steps; it costs almost nothing and removes a whole class of slow failures.
Which representation, when
There is no best representation, only the best for a job. A topological theorem says so: no continuous, one-to-one description of by three numbers exists, so every 3-number representation has a singularity somewhere, and the 4-number quaternion pays for smoothness with the double cover.
| Representation | Numbers | Good for | Watch out for |
|---|---|---|---|
| Rotation matrix | 9 | Rotating many points; composing with translations in transforms; clear meaning (columns are axes) | Drifts off ; 9 numbers to store and send |
| Unit quaternion | 4 | Composing, storing and sending orientations; interpolation (slerp); IMU filters | and ; storage order or ; Hamilton or JPL |
| Rotation vector (axis–angle) | 3 | Small increments, gyro integration, corrections in estimators and optimisers | Axis undefined at ; ambiguous at |
| Euler angles (roll, pitch, yaw) | 3 | Human input and display; configuration files and URDF; vehicles far from the singularity | Gimbal lock; twelve sequences; never interpolate or average them |
A common professional pattern combines them: store orientations as quaternions, compute with matrices when transforming points, update with rotation vectors (the estimator's state includes a small 3-vector error, applied through the exponential map), and show Euler angles to people. The "micro Lie theory" paper in the references describes this pattern for estimation, and libraries such as Eigen (C++), SciPy's spatial.transform.Rotation (Python), Sophus and manif (C++ Lie-group libraries) implement it.
Machine learning added a new requirement. A neural network that outputs a rotation needs a representation in which nearby rotations have nearby outputs everywhere. Zhou and colleagues showed in 2019 that every 3- and 4-number representation fails this somewhere, and proposed outputting six numbers, two columns of the matrix, then completing them to a rotation with Gram–Schmidt and a cross product. Many pose-estimation networks and robot policies now do exactly that.
Common misconceptions
Misconception
"Interpolating or averaging Euler angles is fine." It works only for small angles about a single axis. Averaging yaw and gives , the opposite direction, and near gimbal lock the angles can jump by tens of degrees between orientations that are almost the same. Interpolate with slerp; average quaternions with a method designed for it (for example, the principal eigenvector of the sum of ).
Misconception
" and are different rotations, so two estimates that differ in sign disagree." They are the same rotation. Comparisons should use , and code that interpolates or averages must first flip signs so that all quaternions lie in the same hemisphere.
Misconception
"Gimbal lock means the robot cannot rotate that way." The robot can; the three-angle description is singular there. Switch representation and the problem disappears, unless your hardware is a three-ring mechanical gimbal, where it is physical.
Misconception
"A quaternion read from a ROS message can be passed straight to my maths library." Only if both agree on the order. A ROS message stores a 90° yaw as x = 0, y = 0, z = 0.7071, w = 0.7071; read as , the same four numbers mean a turn about the axis . Convert field by field, by name.
A short history
Leonhard Euler proved in 1775 that every rotation of a rigid body about a fixed point is a rotation about some axis, and introduced the angles that carry his name to describe spinning bodies. Olinde Rodrigues published his formula, and a set of four parameters for composing rotations, in 1840. Hamilton discovered quaternions on 16 October 1843 while walking along the Royal Canal in Dublin and scratched the multiplication rule into Broome Bridge as he passed; a plaque marks the place today. Quaternions then lost ground to the vector algebra of Gibbs and Heaviside for most of physics, but returned in the 1960s and 1970s in spacecraft attitude control, where they avoided gimbal lock and were cheaper than matrices on small flight computers, and in 1985 in computer graphics, through Ken Shoemake's slerp. Today they are the default orientation format of ROS, of most game engines and of nearly every drone's flight controller.
Exercises
1. Rotations in 3-D and quaternions
Warm-upHumanWhich of these matrices are in , that is, are rotation matrices? Select all that apply.
2. Rotations in 3-D and quaternions
CoreHumanThe unit quaternion , written , represents a rotation. By how many degrees does it rotate?
3. Rotations in 3-D and quaternions
CoreHumanA ROS 2 node receives an orientation as a geometry_msgs/Quaternion with fields x = 0, y = 0, z = 0.7071, w = 0.7071: a yaw of . A programmer copies the fields into an array in the order they appear in the message, [0, 0, 0.7071, 0.7071], and passes it to a function that expects . By how many degrees does the function think the robot is rotated?
4. Rotations in 3-D and quaternions
CoreHumanWith the lesson's convention , what happens at pitch ?
5. Rotations in 3-D and quaternions
Warm-upHumanAn Euler-angle convention is a sequence of three coordinate axes, such as or , in which no two consecutive axes are the same (a repeat would just add two angles). How many such sequences are there?
6. Rotations in 3-D and quaternions
CoreComputationalWrite rpy_to_quat(roll, pitch, yaw) that returns the unit quaternion for , choosing the sign so that . Angles are in radians. The Hamilton product qmul is provided. (ROS's tf2 offers the same conversion as setRPY, but it stores the result as .)
7. Rotations in 3-D and quaternions
StretchComputationalThe starter's slerp is really nlerp: it moves at a varying speed. Rewrite it as true spherical linear interpolation between unit quaternions p and q (stored ), for . It must (1) rotate at constant angular speed, (2) take the shorter way round when , and (3) return a finite unit quaternion when and are equal or nearly equal.
Further reading and resources
- Quaternion kinematics for the error-state Kalman filter · Joan Solà · 2017A careful, free reference on quaternion conventions (Hamilton and JPL), conversions and integration.
- A micro Lie theory for state estimation in robotics · Joan Solà, Jeremie Deray and Dinesh Atchuthan · 2018The Lie-group view of SO(3) and SE(3) that modern estimators use, in under forty pages.
- On the continuity of rotation representations in neural networks · Yi Zhou, Connelly Barnes, Jingwan Lu, Jimei Yang and Hao Li · 2019Why networks that output Euler angles or quaternions struggle, and the 6-D alternative.
- Modern Robotics: Mechanics, Planning, and Control · Kevin M. Lynch and Frank C. Park · 2017Chapter 3 covers rotation matrices, exponential coordinates and the matrix logarithm.
- REP 103: Standard Units of Measure and Coordinate ConventionsHow ROS represents orientation, and its preference for quaternions.