Meet the quaternion: four numbers for one turn
A quaternion is four numbers, [w, x, y, z]. For a rotation, they are just the axis and the angle from lesson 2, written in a clever way. In this lesson we learn to read them.
4.1The formula
A quaternion has one real part and three imaginary parts:
A simple case first. In lesson 3, a turn by θ in the plane was the number cos θ + i sin θ. A turn about the z axis is the same kind of turn, in the x-y plane. Its quaternion looks almost the same, with k for the z axis and half the angle (we see why in 4.3):
About x it would be i instead of k, about y it would be j. For any axis \(\mathbf n = (n_x, n_y, n_z)\) we take the mix \(n_x i + n_y j + n_z k\):
w holds the angle. The vector part (x, y, z) points along the axis.
4.2How to read a quaternion
- w close to 1: a small turn. The object is almost where it started.
- w = 0: a half turn, 180°.
- (x, y, z): the direction of the axis. Its length is \(\sin\frac{\theta}{2}\).
- The length of a quaternion is \(\sqrt{w^2 + x^2 + y^2 + z^2}\). For a rotation it is always 1, because \(\cos^2 + \sin^2 = 1\). We call it a unit quaternion.
- Four numbers, but the length must be 1, so only three are free. That’s the same count as in lesson 2.
| [1, 0, 0, 0] | no turn at all |
| [0.707, 0, 0, 0.707] | 90° about z: a quarter turn to the left |
| [0.707, 0, 0.707, 0] | 90° about y: the front points straight down |
| [0, 1, 0, 0] | 180° about x: upside down |
4.3Why half the angle?
Many people find this part confusing, so let’s be clear. In lesson 6 we will see that turning a vector uses q twice, once on each side of the vector, and each use turns it by half the angle. Half plus half gives the full angle θ.
Because of the half angle, 360° gives \(w = \cos 180° = -1\), so q = [−1, 0, 0, 0]. The object is back where it started, but q is not [1, 0, 0, 0]. Only after 720° do we get the same numbers again. So q and −q describe the same orientation. In code, this matters when we compare or blend two quaternions. We come back to it in lesson 10.
- A rotation of θ about axis n is q = [cos(θ/2), n·sin(θ/2)].
- A rotation quaternion always has length 1.
- q and −q are the same orientation.
✓Check yourself
Which rotation is q = [0.5, 0.5, 0.5, 0.5]?
w = cos(θ/2) = 0.5, so θ/2 = 60° and θ = 120°. The axis is (0.5, 0.5, 0.5) made unit length: (1, 1, 1)/√3. So 120° about the diagonal.
Write the quaternion for 180° about z.
[cos 90°, 0, 0, sin 90°] = [0, 0, 0, 1].
Your program prints q = [−0.98, 0.1, 0, −0.17]. Is the object turned by a lot?
No. −q = [0.98, −0.1, 0, 0.17] has w close to 1, so it is a small turn, about 23°.
+Sources and further reading
- J. Solà, "Quaternion kinematics for the error-state Kalman filter", 2017
chapter 1 and 2: definition, the half angle and the double cover - G. Sanderson and B. Eater, "Visualizing quaternions: an explorable video series"
interactive videos on what the four numbers do