Turn a drone through a loop. At 90° its roll and yaw readings jump from 0° to 180° in one step. Over the same step, the four quaternion numbers move by about 0.01.
Drag the drone through 90° and watch the Euler readout jump. Then switch to the quaternion and do it again. Then we build, piece by piece, rotation matrices, order, gimbal lock, axis-angle, quaternions, rigid transforms and the safe way to nudge an orientation.
You need vectors and matrix times vector and sine and cosine. For the flat 2D case first, read Rigid-Body Transforms, SE(2) and SE(3). We build the 3D rest from zero.
Foundations for robotics and state estimation. We checked every matrix, quaternion and worked number on this page with NumPy and scipy.spatial.transform.
Exact maths: the drone turns about the world y axis. Euler angles use the ZYX order (yaw, then pitch, then roll); the quaternion is Hamilton, scalar first. Red marks a jump in the readout, not in the drone.
Chapter 0
Turn a phone twice, swap the order, and land in a different pose
A drone gets two corrections: pitch 90°, then yaw 90°. A refactor applies them yaw first. The two numbers are the same. The drone ends up facing a different way.
Position does not behave like this. Walk 3 m east, then 4 m north, and you stand where 4 m north, then 3 m east, puts you. Position changes add, and addition ignores order. An orientation (which way a body faces) changes by turns, and a turn acts on the result of the turn before it.
The warm face is the front (body x). The blue face is the top (body z). Press one order, then the other, and compare the faces.
Exact maths. Pitch is a turn about the world y axis, yaw about the world z axis, both +90°.
Work the number. Pitch then yaw sends the front to (0, 0, −1), straight down, and the top to (0, 1, 0). Yaw then pitch sends the front to (0, 1, 0) and the top to (1, 0, 0). Same two turns, two poses.
| Quantity | Changes combine by | Order matters? |
|---|---|---|
| Position | adding vectors | no |
| Orientation | multiplying matrices or quaternions | yes |
The symptom is a vehicle that tips the wrong way after a harmless-looking refactor. To measure it, apply both orders to the vector (1, 0, 0) in a unit test and compare. The fix is one documented order, tested, in one function.
Chapter 1
Turn a frame about one axis and read where its three arrows land
In the plane, a rotation is a 2 by 2 matrix built from where the two axis arrows land (the SE(2) lesson builds it). In 3D the same idea gives a 3 by 3 matrix. A rotation matrix R is a 3 by 3 matrix whose three columns are where the x, y and z arrows land after the turn.
The simplest turns leave one axis alone. Call the angle of a turn about z γ (gamma). The z arrow stays put; x and y turn in their plane, like the 2D case.
R-z of gamma is the three by three matrix: cos gamma, minus sine gamma, zero; sine gamma, cos gamma, zero; zero, zero, one.
To turn a vector v by gamma about z, scale each column by the matching part of v. Column 1 takes v's x part, column 2 its y part, column 3 its z part. Add the three.
Gamma = 30°: cos is 0.866, sin is 0.5. The vector (1, 0, 0) lands on column 1, (0.866, 0.5, 0). Its length is still 1.
Grey arrows are the world axes. Coloured arrows are the turned axes, and each one is a column of the matrix below. Pick an axis and drag the angle.
Exact maths. Right-handed axes, z up.
Every rotation matrix passes two checks. Together they define the set SO(3), all 3D rotations.
| Check | What it means | For Rz(30°) |
|---|---|---|
| RTR = I | columns have length 1 and meet at right angles; so R−1 = RT | 0.866 × (−0.5) + 0.5 × 0.866 = 0 |
| det R = +1 | a turn, not a mirror (a mirror has −1) | 0.866² + 0.5² = 1 |
This page fixes its conventions once. Every device follows them.
| Choice | This page |
|---|---|
| Axes | right-handed, z up |
| Active or passive | active: we turn the object; the axes stay |
| Vectors | columns, so R acts as R v |
| Positive angle | counter-clockwise when the axis points at you |
The symptom is a "rotation" that slowly shrinks or skews an object over many updates. Rounding has pulled the columns off length 1. To measure it, log the size of RTR − I. The fix is to re-orthonormalise R now and then, or to store a quaternion (Chapter 5).
Chapter 2
Chain two turns, then see that body axes reverse the order
Two turns in a row are one turn. Call the first turn R1 (R-one) and the second R2 (R-two). The vector v first meets R-one, so R-one sits next to it.
v-prime equals R-two times R-one times v.
Apply R-one to v. Then apply R-two to the result. Read the product from right to left.
R-one is 90° about x, R-two is 90° about z, v = (1, 0, 0). R-one leaves v at (1, 0, 0); R-two sends it to (0, 1, 0). Swap them: Rz first gives (0, 1, 0), then Rx gives (0, 0, 1).
There is a second trap. A turn can be about a world axis, fixed in the room. Or it can be about a body axis, fixed to the object, so it moved with the first turn. Turns about world axes are extrinsic; turns about body axes are intrinsic.
Pick a recipe and press Play. Watch the warm front arrow. Two of the three recipes end in the same pose.
Exact maths, both turns +90°.
The rule: turning about body axes in one order equals turning about world axes in the reverse order. Body x then body y is RxRy, the same product as world y then world x. Both send the front to (0, 1, 0).
The symptom is code ported between libraries that gives a mirrored or twisted pose. One library meant world axes, the other body axes. To measure it, push (1, 0, 0) through both with angles of 90°. The fix is to name the convention in the function name, for example euler_zyx_intrinsic.
Chapter 3
Store an orientation as three angles, then watch two of them fuse at 90°
Three numbers are easy to read: "nose up 15°, banked 10°". Call the turn about x the roll φ (phi), about y the pitch θ (theta), about z the yaw ψ (psi). Stacked in the aerospace order, they make one matrix.
R equals R-z of psi, times R-y of theta, times R-x of phi.
Roll by phi about world x, then pitch by theta about world y, then yaw by psi about world z. By Chapter 2 that equals yaw, then pitch, then roll about body axes: the "ZYX" or "3-2-1" order.
Set theta = 90°. Roll 40° with yaw 10° gives the matrix [[0, 0.5, 0.866], [0, 0.866, −0.5], [−1, 0, 0]]. Roll 30° with yaw 0° gives the same matrix.
At pitch 90° the matrix depends only on roll minus yaw. Any pair with the same difference gives the same pose, so one of the three numbers does nothing. This is gimbal lock. In a mechanical gimbal (three nested rings), the roll ring's axis swings onto the yaw ring's axis.
Blue is the yaw ring, teal the pitch ring, warm the roll ring. Drag the pitch toward 90° and watch the warm axis meet the blue one.
Exact maths. The read-out turns the body by 0.5° about its own z axis and reads the Euler angles again with the standard ZYX formulas.
Near the lock, reading angles back from a matrix divides by cos θ, which is near zero. At pitch 45°, a 0.5° body nudge moves yaw by 0.7°. At pitch 89.9°, the same nudge moves yaw by 60°. The symptom is jittery roll and yaw on a smooth flight. The fix is to keep the state as a quaternion and show Euler angles only on screens.
Chapter 4
Describe any turn as a spin about one line, and build its matrix
Euler proved that every 3D rotation is one turn about one fixed line through the origin. So a rotation needs only a unit axis n and an angle θ. Pack them as one vector, the rotation vector θn: its direction is the axis, its length the angle.
To build the matrix we need the cross product as a matrix. The hat operator turns n = (nx, ny, nz) into a skew-symmetric matrix [n]×, so that [n]×v = n × v. Its rows are [0, −nz, ny], [nz, 0, −nx] and [−ny, nx, 0].
R equals I, plus sine theta times K, plus one minus cos theta, times K squared.
Split v into a part along the axis n and a part across it. The part along n stays. The part across turns by theta in its own plane, which is the 2D rotation again.
Axis n = (1, 1, 1)/√3, theta = 120°, v = (0, 0, 1). The three terms give (0, 0, −0.5) + (0.5, −0.5, 0) + (0.5, 0.5, 0.5) = (1, 0, 0). A third of a turn about the cube's diagonal sends z to x.
Purple is the axis n. Pink is v = (0, 0, 1) turned by theta. Pick an axis and drag theta; the faint circle is every place v can reach.
Exact maths: Rodrigues' formula, checked against Rotation.from_rotvec.
At theta = 0 every axis gives the identity, so no single axis exists. Code that divides by theta to find n returns garbage for a body at rest. To measure it, feed the zero rotation to your conversion. The fix is a small-angle branch: below about 10−8 rad, return the identity.
Chapter 5
Store a turn in four numbers that never lock and combine with one product
Axis-angle has no lock, but two axis-angle turns have no simple combination rule. A matrix combines well but carries nine numbers for three degrees of freedom. A unit quaternion sits between: four numbers (w, x, y, z) with w² + x² + y² + z² = 1.
Build it from the axis n and the angle θ of Chapter 4.
q equals cos of theta over two, then sine of theta over two times n.
Halve the angle theta. Put its cosine in w. Put its sine, times the axis n, in x, y and z.
A 60° turn about z: half is 30°. q = (0.866, 0, 0, 0.5). Check: 0.866² + 0.5² = 1.
Why half? Because q and −q give the same turn. A full 360° turn takes q to −q, and only 720° brings q home. This is the double cover. Two quaternions combine with the Hamilton product. Split each into a scalar w and a vector part v.
q-one times q-two equals: w-one w-two minus v-one dot v-two; then w-one v-two plus w-two v-one plus v-one cross v-two.
Multiply the scalars and subtract the dot product of the vector parts. For the new vector part, add each vector scaled by the other's scalar, plus their cross product.
q-one = 90° about z = (0.707, 0, 0, 0.707); q-two = 90° about x = (0.707, 0.707, 0, 0). Scalar: 0.5 − 0 = 0.5. Vector: (0.5, 0, 0) + (0, 0, 0.5) + (0, 0.5, 0) = (0.5, 0.5, 0.5). That is 120° about (1, 1, 1), and it sends x to y.
Drag the angle from 0° to 720°. The frame comes home at 360°. Watch the purple w bar: it reaches −1 there and returns to +1 only at 720°.
Exact maths, Hamilton quaternion, scalar first.
To turn a vector v, write it as the quaternion (0, v) and compute q ⊗ (0, v) ⊗ q*. Here the conjugate q* is (w, −x, −y, −z). The result is Rodrigues' formula in other clothes.
Libraries disagree on the layout. SciPy stores (x, y, z, w), scalar last. The JPL convention in some estimation papers also defines the product with the opposite handedness, so compositions run in reverse. The symptom is a pose that turns the wrong way after a library swap. To measure it, convert 90° about z both ways and compare. The fix is one conversion function at each boundary.
Chapter 6
Blend two quaternions and compare a steady turn with one that rushes in the middle
A camera must ease from one orientation to another over two seconds. Call the start quaternion q0 (q-zero), the end q1 (q-one), and the fraction of time passed t, from 0 to 1. Unit quaternions live on a 4D sphere. The quick blend, nlerp, mixes them in a straight line and rescales to length 1. The straight line cuts across the sphere, so the turn rushes in the middle.
Slerp (spherical linear interpolation) walks the great arc at a steady rate. Call the angle between the two quaternions on the sphere Ω (omega), found from cos Ω = q0·q1.
Slerp of q-zero, q-one and t equals: sine of one minus t, times omega, times q-zero, plus sine of t omega times q-one, all over sine omega.
Weight q-zero and q-one by sines of how far along the arc you are. Divide by sine omega. Equal steps in t give equal steps of turn.
q-zero is no turn; q-one is 180° about z, so omega = 90°. At t = 0.25, slerp gives a 45° turn, a quarter of 180°. Nlerp gives 36.9°.
Left: the quaternion circle, with the purple arc (slerp) and the grey chord (nlerp). Right: turn angle against t. Drag t, then widen the end turn.
Exact maths. Both ends are turns about z, so every quaternion here lies in the (w, z) plane and the 4D sphere becomes this circle.
The symptom is a camera that speeds up mid-turn, or that takes the long way round. For a 180° end turn, nlerp turns at twice its end speed in the middle. To measure it, plot turn angle against t. The fix is slerp for far-apart keyframes, and a sign flip when q0·q1 < 0 so the arc is the short one. For close keyframes, nlerp is cheaper and the error is tiny.
Chapter 7
Chain a world, a robot base and a camera, and carry one point through
A camera sits on a robot base, and the base sits in a room. A feature seen by the camera needs room coordinates. Each link is a rigid transform: a rotation R plus a shift t. The trick is to pad each point with a 1, (x, y, z, 1). These are homogeneous coordinates.
T is the four by four block matrix: R and t on top, a row of zeros and a one below. T times p-and-one equals R p plus t, and one.
Rotate the point p by R. Then add the shift t. The padded 1 lets one matrix product do both, so chains become products.
R = Rz(90°), t = (1, 0, 0), p = (0.2, 0, 0.5). R p = (0, 0.2, 0.5). Add t: (1, 0.2, 0.5).
Name each transform "to from": Twb (T-w-b) is "world from base". It takes base coordinates to world coordinates. Chains cancel the inner letters: Twc = TwbTbc. The inverse flips the name: Tbw = Twb−1, with rotation RT and shift −RTt.
Grey is the world, the middle frame is the base, the small frame is the camera. The pink point is fixed 0.2 m along the camera's x. Turn the base and tilt the camera.
Illustrative rig: the base stands 1 m along world x; the camera is 0.5 m above the base origin.
Work the default by hand. Twb has Rz(90°) and t = (1, 0, 0). Tbc has no turn and t = (0, 0, 0.5). The camera sits at Rz(90°)(0, 0, 0.5) + (1, 0, 0) = (1, 0, 0.5). The point (0.2, 0, 0) in the camera lands at (1, 0.2, 0.5) in the world. The inverse brings (1, 0.2, 0.5) back to (0.2, 0, 0).
The symptom is a pose that looks mirrored or offset while every number looks plausible. Someone used Twb where Tbw belongs. To measure it, send the base origin (0, 0, 0) through Twb: you must get the base's position in the world. The fix is the "to from" naming, so that inner letters always match.
Chapter 8
Add a small correction the wrong way and the right way, and watch the columns
A filter or an optimiser corrects its orientation estimate R hundreds of times a second. The tempting update adds a small matrix to R. The sum is no longer a rotation. Instead, write the correction as a small rotation vector ω (omega): axis times angle, in radians. Turn it into a rotation and multiply.
R box-plus omega equals R times exp of the hat of omega.
Turn the small correction omega into a real rotation with exp. Multiply the estimate R by it. A product of two rotations is a rotation, so the result never leaves SO(3).
R = Rz(60°), omega = (0, 0, 0.3) rad, which is 17.19°. The update gives a turn of 77.19°, columns of length 1.000, det 1.000.
Left: the first column of R after ten updates, in the xy plane. Red adds R[ω]× each time; green multiplies by exp([ω]×). Right: that column's length. Drag the size of the correction.
Exact maths. R starts at Rz(60°); the correction is about z.
The log map runs the other way: from R back to omega. The angle comes from the trace of R (the sum of its diagonal).
Theta equals arc cos of, trace R minus one, over two.
Add the diagonal of R, subtract 1, halve it, take the arc cos. That is theta. The axis is the vector inside (R − RT)/(2 sin theta), read through the hat pattern.
R = Rz(30°): trace = 0.866 + 0.866 + 1 = 2.732. (2.732 − 1)/2 = 0.866, arc cos gives 30°. R − RT over 2 sin 30° gives the axis (0, 0, 1).
SE(3) has an exp too. A twist (ω, ρ) holds a turn ω and a drive ρ. Its rotation is exp([ω]×); its shift is t = Vρ, where V = I + ((1 − cosθ)/θ²)[ω]× + ((θ − sinθ)/θ³)[ω]ײ. Take ω = (0, 0, π/2) and ρ = (1, 0, 0). A robot drives 1 m on a quarter circle and ends at t = (0.637, 0.637, 0), not (1, 0, 0).
With a 17° correction, R + R[ω]× gives columns of length 1.044 and det 1.09. After ten updates the columns reach 1.54. The symptom is a pose that grows or shears over time. To measure it, log |det R − 1|. The fix is the ⊕ update.
Chapter 9
Pose a world, base, camera and IMU chain, and read one rotation three ways
Here is a robot's sensor chain: World, Base, Camera, IMU. Each joint has one angle. The IMU's orientation in the world is Rwi = Rz(yaw) Ry(pitch) Rx(roll). That is the ZYX Euler matrix of Chapter 3. So the Euler readout should give back the three sliders.
Drag the camera pitch to 90° with the Euler readout on. Then switch to the quaternion and drag through 90° again.
Point fixed in
IMU orientation readout
| Frame | The pink point in that frame (m) |
|---|
Illustrative rig: base 1.4 m along world x; camera 0.7 m above the base; IMU 0.3 m ahead and 0.15 m above the camera. The point sits at (1.9, 0.3, 0.5), (0.5, 0, 0.2), (0.3, 0, 0) or (0.1, 0, 0) in the frame it is fixed in.
At the defaults the readouts agree on one rotation. Euler gives roll −15°, pitch 20°, yaw 30°. Axis-angle gives 40.8° about (−0.48, 0.38, 0.79). The quaternion is (0.937, −0.169, 0.133, 0.275). The point fixed 0.1 m ahead of the IMU sits at (1.770, 0.214, 0.704) in the world.
Push the pitch to 90°. The Euler readout can no longer split roll from yaw, so it reports yaw 0° and folds both into roll. The quaternion and the axis-angle move on smoothly. One pose, three readings; only one of them panics.
Predict before you look. With the point fixed in the IMU, nudge the base yaw. Only the World row changes: base, camera and IMU still hold the same rigid shape. Fix the point in the World instead, and the other three rows change.
Chapter 10
Pick a representation, fix the conventions, and keep the code
Every representation answers one question: which way does this body face? Each trades size for trouble spots.
| Representation | Numbers | Trouble spot | Combines by | Use it for |
|---|---|---|---|---|
| Euler angles (ZYX) | 3 | lock at pitch ±90° | convert to a matrix first | logs, dashboards, sliders |
| Rotation vector (axis-angle) | 3 | no single axis at 0; n and −n at 180° | convert first | small corrections ω in filters and optimisers |
| Unit quaternion | 4, length 1 | none; q and −q are the same turn | one Hamilton product | attitude state, gyro integration, slerp |
| Rotation matrix | 9, orthogonal | drifts off SO(3) with rounding | matrix product | turning many points, proofs |
| SE(3) transform | rotation + 3 | those of its rotation | 4 by 4 product | frame chains, extrinsics, kinematics |
| Term | One line | Number to remember |
|---|---|---|
| SO(3) | all 3D rotations: RTR = I, det R = +1 | 3 degrees of freedom |
| Gimbal lock | at pitch ±90° roll and yaw act on one axis | 0.5° nudge at 89.9° moves yaw 60° |
| Rodrigues | R = I + sinθ K + (1 − cosθ)K² | 120° about (1, 1, 1) sends z to x |
| Double cover | q and −q are one turn | 720° brings q home |
| Slerp | steady turn along the great arc | nlerp at t = 0.25 of 180°: 36.9° |
| Log map | θ = arccos((tr R − 1)/2) | trace 2.732 means 30° |
| Question | This page | Watch for |
|---|---|---|
| Quaternion layout | (w, x, y, z), scalar first | SciPy and ROS messages store (x, y, z, w) |
| Quaternion product | Hamilton | JPL papers reverse the product order |
| Euler order | ZYX intrinsic = XYZ extrinsic | SciPy: capital letters mean intrinsic |
| Update side | R exp([ω]×), body frame | exp([ω]×) R, world frame |
pythonimport numpy as np from scipy.spatial.transform import Rotation as Rot def hat(w): # 3-vector -> 3x3 skew matrix return np.array([[0, -w[2], w[1]], [w[2], 0, -w[0]], [-w[1], w[0], 0]]) def exp_so3(w): # rotation vector (3,) -> R (3,3) th = np.linalg.norm(w) if th < 1e-8: return np.eye(3) + hat(w) # small-angle branch K = hat(w / th) return np.eye(3) + np.sin(th) * K + (1 - np.cos(th)) * K @ K def log_so3(R): # R (3,3) -> rotation vector (3,), angle below 180 deg th = np.arccos(np.clip((np.trace(R) - 1) / 2, -1, 1)) if th < 1e-8: return np.zeros(3) v = np.array([R[2,1] - R[1,2], R[0,2] - R[2,0], R[1,0] - R[0,1]]) return th * v / (2 * np.sin(th)) def qmul(a, b): # Hamilton, (w, x, y, z): a after b w1, v1, w2, v2 = a[0], a[1:], b[0], b[1:] return np.r_[w1*w2 - v1 @ v2, w1*v2 + w2*v1 + np.cross(v1, v2)] R = Rot.from_euler('ZYX', [30, 20, -15], degrees=True).as_matrix() # yaw, pitch, roll R = R @ exp_so3(np.radians([0, 0, 5])) # safe update: R (+) omega x, y, z, w = Rot.from_matrix(R).as_quat() # SciPy order is scalar LAST
Now press Present or Teach and explain from memory why the Euler readout jumps at 90° and the quaternion does not. Then go back to the hero, fly the loop again, and say which chapter explains each line on the plot.