We now have three ways of describing a rotation, and none of them is perfect. Euler angles are readable but suffer from gimbal lock; matrices are composed with a simple product but spend nine numbers on three degrees of freedom and degrade with rounding; the axis-angle pair is compact and intuitive, but does not know how to compose. Quaternions are the representation that practically every 3D engine uses internally because they bring together the virtues we are missing: four numbers, no gimbal lock, a multiplication rule of their own for composing rotations, trivial to normalize and—as we will see in the next lesson—ideal for interpolating. They have a reputation for being mysterious, but they are not if you reach them by the right route: a unit quaternion is, quite simply, an axis and an angle stored in a way that lets them be multiplied.
The code assumes that normalize, dot_product and cross_product (Module 3), the functions from the two previous lessons (euler_to_matrix, matrix_to_euler, rotate_axis_angle, axis_angle_matrix, matrix_to_axis_angle), rotation_matrix_z and the data ship_orientation and ship are already defined.
From complex numbers to quaternions
In 2D there is a very elegant way of rotating: complex numbers. A point \((x, y)\) is identified with the number \(x + y,i\), where \(i^2 = -1\), and a rotation through an angle \(\theta\) is represented by the complex number of modulus 1
\[ z = \cos\theta + i,\sin\theta \]
Rotating the point is multiplying: \((\cos\theta + i\sin\theta)(x + yi) = (x\cos\theta - y\sin\theta) + (x\sin\theta + y\cos\theta),i\), which are exactly the two rows of the 2D rotation matrix. And composing two rotations is multiplying their complex numbers, so the angles add up. Two numbers instead of a 2×2 matrix, and one product instead of sines and cosines.
In the 19th century, the Irish mathematician William Rowan Hamilton spent years searching for the equivalent for space. The natural thing seemed to be to add a second imaginary unit and work with triples \(a + bi + cj\), but there is no way of defining a product that works. The solution, which he found in 1843, requires three imaginary units and, therefore, four numbers: the quaternions. The extra dimension makes sense in hindsight: a 3D rotation is an axis and an angle, and four numbers subject to one condition (norm 1) leave exactly the three degrees of freedom required.
Definition: scalar part and vector part
A quaternion is an expression of the form
\[ q = w + x,i + y,j + z,k \]
with \(w, x, y, z\) real numbers and three imaginary units \(i\), \(j\), \(k\) that satisfy Hamilton's fundamental rule:
\[ i^2 = j^2 = k^2 = i,j,k = -1 \]
From it follow the products of the units with one another, which obey the same cyclic pattern \(i \to j \to k \to i\) as the cross product:
| Product | Result | Product in reverse order | Result |
|---|---|---|---|
| \(i,j\) | \(k\) | \(j,i\) | \(-k\) |
| \(j,k\) | \(i\) | \(k,j\) | \(-i\) |
| \(k,i\) | \(j\) | \(i,k\) | \(-j\) |
In cyclic order, the product of two units gives the third; in the opposite order, the third with its sign changed. The immediate consequence is that the quaternion product is not commutative, just like the matrix product. For objects that are going to represent rotations, that is not a flaw: it is mandatory.
It is very practical to split the quaternion into two pieces:
\[ q = (w,\ \mathbf{u}) \qquad \text{with}\quad w\ \text{(a number)} \quad\text{and}\quad \mathbf{u} = (x, y, z)\ \text{(a vector)} \]
The number \(w\) is the scalar part and the vector \(\mathbf{u}\), the vector part.
- A quaternion with \(\mathbf{u} = \mathbf{0}\) is an ordinary real number.
- A quaternion with \(w = 0\) is called pure, and it is the way to bring a 3D vector into the world of quaternions: \(\mathbf{v} = (v_x, v_y, v_z)\) becomes \(v_x i + v_y j + v_z k\).
Storage convention. In mini3d a quaternion is a NumPy array of four elements in the order [w, x, y, z]: the scalar part first. Take care when exchanging data: many libraries and file formats use the order [x, y, z, w], with the scalar part at the end. It is the quaternion equivalent of the axis convention for Euler angles: it must always be checked.
Operations: sum, Hamilton product, conjugate, norm and inverse
Sum and multiplication by a number
Component by component, as with vectors: \((w_1, \mathbf{u}_1) + (w_2, \mathbf{u}_2) = (w_1 + w_2,\ \mathbf{u}_1 + \mathbf{u}_2)\). The sum has no meaning as a rotation, but we will need it for interpolating.
Hamilton product
You multiply as with polynomials, respecting the order of the factors and applying the table of units. Let's start with two pure quaternions, \(\mathbf{a}\) and \(\mathbf{b}\). When \((a_x i + a_y j + a_z k)(b_x i + b_y j + b_z k)\) is expanded, the terms with the same unit give \(-a_x b_x - a_y b_y - a_z b_z\), and the cross terms group into \((a_y b_z - a_z b_y),i + (a_z b_x - a_x b_z),j + (a_x b_y - a_y b_x),k\). We recognize the two operations of Module 3:
\[ \mathbf{a},\mathbf{b} = \big(-,\mathbf{a} \cdot \mathbf{b},\ \ \mathbf{a} \times \mathbf{b}\big) \]
The quaternion product contains, at the same time, the dot product and the cross product. Adding the scalar parts gives the general formula:
\[ \boxed{\ (w_1, \mathbf{u}_1),(w_2, \mathbf{u}_2) = \big(w_1 w_2 - \mathbf{u}_1 \cdot \mathbf{u}_2,\ \ w_1,\mathbf{u}_2 + w_2,\mathbf{u}_1 + \mathbf{u}_1 \times \mathbf{u}_2\big)\ } \]
The only term that distinguishes \(p,q\) from \(q,p\) is the cross product, which changes sign: that is why the product does not commute (except when the vector parts are parallel). It is, however, associative, \((p,q),r = p,(q,r)\), and distributive over the sum.
Example. Let \(p = 1 + 2i + k = (1,\ (2, 0, 1))\) and \(q = 2 + j - k = (2,\ (0, 1, -1))\).
- Scalar part: \(1 \cdot 2 - (2, 0, 1) \cdot (0, 1, -1) = 2 - (-1) = 3\).
- Cross product: \((2, 0, 1) \times (0, 1, -1) = (0 \cdot (-1) - 1 \cdot 1,\ 1 \cdot 0 - 2 \cdot (-1),\ 2 \cdot 1 - 0) = (-1, 2, 2)\).
- Vector part: \(1 \cdot (0, 1, -1) + 2 \cdot (2, 0, 1) + (-1, 2, 2) = (3, 3, 3)\).
So \(p,q = 3 + 3i + 3j + 3k\). In the opposite order only the sign of the cross product changes: \(q,p = (3,\ (4, 1, 1) - (-1, 2, 2)) = 3 + 5i - j - k\). Different.
Conjugate, norm and inverse
| Operation | Definition | Properties |
|---|---|---|
| Conjugate | \(q^* = (w,\ -\mathbf{u})\) | \((p,q)^* = q^,p^\) (it reverses the order, like the transpose) |
| Norm | \(\lVert q \rVert = \sqrt{w^2 + x^2 + y^2 + z^2}\) | \(q,q^* = \lVert q \rVert^2\) (a real number); \(\lVert p,q \rVert = \lVert p \rVert,\lVert q \rVert\) |
| Inverse | \(q^{-1} = q^* / \lVert q \rVert^2\) | \(q,q^{-1} = q^{-1},q = 1\) |
That \(q,q^*\) is real can be seen in the product formula: the scalar part is \(w^2 + \mathbf{u} \cdot \mathbf{u}\) and the vector part, \(-w\mathbf{u} + w\mathbf{u} - \mathbf{u} \times \mathbf{u} = \mathbf{0}\). In the example, \(\lVert p \rVert^2 = 6\), \(\lVert q \rVert^2 = 6\) and \(\lVert p,q \rVert^2 = 9 \cdot 4 = 36\): the norms multiply.
A quaternion of norm 1 is called a unit quaternion. For these, the inverse is the conjugate: \(q^{-1} = q^*\). It is the quaternion version of "the inverse of an orthogonal matrix is its transpose", and it costs three sign changes.
import numpy as np
def quaternion_product(p, q):
"""Hamilton product p q of two quaternions [w, x, y, z]."""
w1, u1 = p[0], np.asarray(p[1:], dtype=float)
w2, u2 = q[0], np.asarray(q[1:], dtype=float)
scalar = w1 * w2 - dot_product(u1, u2)
vector = w1 * u2 + w2 * u1 + cross_product(u1, u2)
return np.concatenate(([scalar], vector))
def quaternion_conjugate(q):
q = np.asarray(q, dtype=float)
return np.array([q[0], -q[1], -q[2], -q[3]])
def quaternion_normalize(q):
"""Unit quaternion with the same 'direction' as q."""
q = np.asarray(q, dtype=float)
return q / np.sqrt(np.sum(q * q))
p = np.array([1.0, 2.0, 0.0, 1.0])
q = np.array([2.0, 0.0, 1.0, -1.0])
print(quaternion_product(p, q), quaternion_product(q, p))
print(quaternion_product(p, quaternion_conjugate(p)))
i, j, k = [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]
print(quaternion_product(i, j), quaternion_product(j, i), quaternion_product(i, i))The function is a transcription of the boxed formula. The last line reproduces the table of units: \(i,j = k\), \(j,i = -k\), \(i^2 = -1\).
Unit quaternions: from axis-angle to quaternion
Rotations are represented by unit quaternions. The one that corresponds to the rotation through an angle \(\theta\) about the unit axis \(\mathbf{k}\) is
\[ \boxed{\ q = \left(\cos\frac{\theta}{2},\ \ \sin\frac{\theta}{2}\ \mathbf{k}\right)\ } \]
It is a unit quaternion because \(\cos^2\frac{\theta}{2} + \sin^2\frac{\theta}{2},\lVert \mathbf{k} \rVert^2 = 1\). It can almost be read at a glance: the vector part points along the axis and the scalar part tells us about the angle. The only striking thing is that the half angle appears; we will see why in a moment.
| Rotation | Quaternion \([w, x, y, z]\) |
|---|---|
| None (identity) | \([1, 0, 0, 0]\) |
| 180° about X | \([0, 1, 0, 0]\), that is, \(i\) |
| 90° about Y | \([0.7071,\ 0,\ 0.7071,\ 0]\) |
| \(\theta\) about Z | \([\cos\frac{\theta}{2},\ 0,\ 0,\ \sin\frac{\theta}{2}]\) |
Example: the ship's orientation. \(N\) is a rotation of 53.13° about Y, with \(\cos\theta = 0.6\). By the half-angle formulas, \(\cos\frac{\theta}{2} = \sqrt{\frac{1 + 0.6}{2}} = \sqrt{0.8} = \frac{2}{\sqrt{5}}\) and \(\sin\frac{\theta}{2} = \sqrt{\frac{1 - 0.6}{2}} = \frac{1}{\sqrt{5}}\). Therefore:
\[ q_N = \frac{1}{\sqrt{5}},(2 + j) \approx [0.8944,\ 0,\ 0.4472,\ 0] \]
def quaternion_from_axis_angle(axis, angle):
"""Unit quaternion [w, x, y, z] of the rotation of `angle` radians about `axis`."""
k = normalize(axis)
half = angle / 2.0
return np.concatenate(([np.cos(half)], np.sin(half) * k))
q_ship = quaternion_from_axis_angle([0.0, 1.0, 0.0], np.arctan2(0.8, 0.6))
print(np.round(q_ship, 4), np.round(q_ship * np.sqrt(5.0), 4))The way back is just as short: from a unit quaternion \((w, \mathbf{u})\) we recover the angle, \(\theta = 2\arccos w\), and the axis, \(\mathbf{u} / \lVert \mathbf{u} \rVert\) (if \(\mathbf{u} = \mathbf{0}\), there is no rotation).
Rotating a vector with (q,v,q^*) and why the half angle
To rotate a vector \(\mathbf{v}\), it is turned into a pure quaternion and "wrapped" between the quaternion and its conjugate:
\[ \boxed{\ \mathbf{v}' = q,\mathbf{v},q^*\ } \]
The result is another pure quaternion, whose vector part is the rotated vector. Why two multiplications, when one was enough for complex numbers? And why the half angle? Both questions have the same answer, and it can be understood with the decomposition we used to derive Rodrigues' formula. Let's write \(q = \cos\alpha + \sin\alpha,\mathbf{k}\) and see what happens to the two parts of \(\mathbf{v}\).
The part parallel to the axis does not change. If \(\mathbf{v}\) is parallel to \(\mathbf{k}\), their cross product is zero and, therefore, \(\mathbf{v}\) and \(q\) commute. Then \(q,\mathbf{v},q^* = \mathbf{v},q,q^* = \mathbf{v}\), because \(q,q^* = 1\).
The perpendicular part rotates through twice \(\alpha\). If \(\mathbf{v}\) is perpendicular to \(\mathbf{k}\), then \(\mathbf{k} \cdot \mathbf{v} = 0\) and the product of the two pure quaternions is just the cross product: \(\mathbf{k},\mathbf{v} = \mathbf{k} \times \mathbf{v}\), whereas \(\mathbf{v},\mathbf{k} = -,\mathbf{k},\mathbf{v}\). That change of sign means that, when \(\mathbf{v}\) is moved to the other side of \(q^*\), the conjugate is undone:
\[ \mathbf{v},q^* = \mathbf{v},(\cos\alpha - \sin\alpha,\mathbf{k}) = (\cos\alpha + \sin\alpha,\mathbf{k}),\mathbf{v} = q,\mathbf{v} \qquad\Longrightarrow\qquad q,\mathbf{v},q^* = q,q,\mathbf{v} = q^2,\mathbf{v} \]
And since \(\mathbf{k}^2 = -1\) (it is a pure unit quaternion), \(q\) is squared like a complex number: \(q^2 = \cos 2\alpha + \sin 2\alpha,\mathbf{k}\). Therefore:
\[ q,\mathbf{v},q^* = \cos 2\alpha\ \mathbf{v} + \sin 2\alpha\ (\mathbf{k} \times \mathbf{v}) \]
which is exactly the rotation of \(\mathbf{v}_\perp\) in its plane, through an angle \(2\alpha\). Adding the two parts gives Rodrigues' formula with \(\theta = 2\alpha\).
That is the explanation: in the "sandwich", the quaternion acts twice, once from each side. On the part perpendicular to the axis the two effects add up (which is why each one must contribute only half the angle); on the parallel part they cancel out. A single multiplication, \(q,\mathbf{v}\), would not do: it does not even give a pure quaternion when \(\mathbf{v}\) has a component along the axis.
Example by hand and check with Rodrigues
Let's rotate the ship's antenna, at the local point \((1, 2, 0)\), with the orientation quaternion \(q_N = (2 + j)/\sqrt{5}\). The result must be the one we have known since Module 1: \(N \cdot \text{antenna} = (0.6,\ 2,\ -0.8)\). To avoid carrying square roots around, we work with \(2 + j\) and divide at the end by \(\sqrt{5} \cdot \sqrt{5} = 5\).
First product, \((2 + j)(i + 2j)\), term by term:
\[ 2i + 4j + j,i + 2,j,j = 2i + 4j - k - 2 = -2 + 2i + 4j - k \]
Second product, by the conjugate \(2 - j\):
\[ (-2 + 2i + 4j - k)(2 - j) = -4 + 2j + 4i - 2,i,j + 8j - 4,j,j - 2k + k,j \]
With \(i,j = k\), \(j,j = -1\) and \(k,j = -i\):
\[ = -4 + 2j + 4i - 2k + 8j + 4 - 2k - i = 0 + 3i + 10j - 4k \]
The scalar part vanishes (the result is pure, as it should be) and, dividing by 5, we get \((0.6,\ 2,\ -0.8)\). Correct.
def rotate_with_quaternion(q, v):
"""Rotate the 3D vector v with the unit quaternion q: vector part of q v q*."""
v_pure = np.concatenate(([0.0], np.asarray(v, dtype=float)))
result = quaternion_product(quaternion_product(q, v_pure), quaternion_conjugate(q))
return result[1:]
antenna = np.array([1.0, 2.0, 0.0])
print(np.round(rotate_with_quaternion(q_ship, antenna), 6))
print(np.round(rotate_axis_angle(antenna, [0.0, 1.0, 0.0], np.arctan2(0.8, 0.6)), 6))
print(np.round(ship_orientation @ antenna, 6))Quaternion, Rodrigues' formula and matrix: three routes, the same point.
Composing rotations is multiplying
Here is the advantage that the axis-angle pair lacked. If we rotate first with \(q_1\) and then with \(q_2\):
\[ q_2,(q_1,\mathbf{v},q_1^),q_2^ = (q_2,q_1),\mathbf{v},(q_2,q_1)^* \]
(using associativity and the fact that \((q_2 q_1)^* = q_1^* q_2^*\)). The composite rotation is the product \(q_2,q_1\), and the product of two unit quaternions is a unit quaternion. The order is the same as with matrices: the quaternion on the right is applied first. All the rules from the previous lessons carry over unchanged:
| With matrices | With quaternions |
|---|---|
| \(R_2,R_1\): first \(R_1\), then \(R_2\) | \(q_2,q_1\): first \(q_1\), then \(q_2\) |
| Inverse: \(R^T\) | Inverse: \(q^*\) |
| Rotation about a world axis: multiply on the left | The same: \(q_{\text{rotation}},q\) |
| Rotation about one of the object's own axes: multiply on the right | The same: \(q,q_{\text{rotation}}\) |
| 9 row-by-column products (27 multiplications) | 16 multiplications |
Example 1. In the previous lesson, to discover that a 90° pitch followed by a 90° yaw is a rotation of 120° about \((1, 1, -1)/\sqrt{3}\) we had to go through matrices. Now one product is enough: \(q_y,q_x\) with \(q_x = (1 + i)/\sqrt{2}\) and \(q_y = (1 + j)/\sqrt{2}\):
\[ q_y,q_x = \tfrac{1}{2},(1 + j)(1 + i) = \tfrac{1}{2},(1 + i + j + j,i) = \tfrac{1}{2},(1 + i + j - k) \]
Scalar part \(\frac{1}{2} = \cos 60°\): an angle of 120°. Vector part proportional to \((1, 1, -1)\): that is the axis.
Example 2: the barrel roll. The ship's orientation after 30° of barrel roll is its orientation \(q_N\) followed by a roll about its own Z axis: multiplication on the right.
quarter = np.radians(90.0)
q_x = quaternion_from_axis_angle([1.0, 0.0, 0.0], quarter)
q_y = quaternion_from_axis_angle([0.0, 1.0, 0.0], quarter)
print(np.round(quaternion_product(q_y, q_x), 4), np.round(quaternion_product(q_x, q_y), 4))
q_roll = quaternion_from_axis_angle([0.0, 0.0, 1.0], np.radians(30.0))
q_barrel_roll = quaternion_product(q_ship, q_roll) # own axis: on the right
print(np.round(q_barrel_roll, 4))
n3 = ship_orientation[:, 2] # the same axis, seen from the world
q_barrel_roll_world = quaternion_product(quaternion_from_axis_angle(n3, np.radians(30.0)), q_ship)
print(np.allclose(q_barrel_roll, q_barrel_roll_world))
right_wing_local = np.array([4.0, 0.0, 0.0])
print(np.round(ship + rotate_with_quaternion(q_barrel_roll, right_wing_local), 4))The first line shows the two orders of Example 1: same angle, different axes. The last one recovers the wing tip at 30° of barrel roll, \((10.078, 5, 3.229)\), which in the previous lesson we computed with a pivot: with an orientation quaternion, the local point \((4, 0, 0)\) is rotated and the ship's position is added to it.
Double cover: (q) and (-q)
If in \(q,\mathbf{v},q^\) we replace \(q\) by \(-q\), the two signs cancel: \((-q),\mathbf{v},(-q)^ = q,\mathbf{v},q^*\). Therefore:
\(q\) and \(-q\) represent the same rotation. Each rotation has exactly two unit quaternions, opposite to each other.
It has a clear geometric reading. Adding a full turn to the angle does not change the rotation, but it does change the quaternion, because the quaternion uses the half angle: \(\cos\frac{\theta + 360°}{2} = -\cos\frac{\theta}{2}\), and likewise for the sine. Or, put another way: \(-q\) is the rotation of \(360° - \theta\) about the opposite axis, \(-\mathbf{k}\); it reaches the same orientation "the other way around".
Practical consequences:
- Comparing orientations. Comparing components is not enough: \(q_1\) and \(q_2\) represent the same orientation if \(q_1 \approx q_2\) or \(q_1 \approx -q_2\). The convenient thing is to use the dot product of the two quaternions as 4-component vectors: they represent the same thing when its absolute value is 1.
- Interpolating. Of the two representatives of the destination, one is "near" the starting point and the other "far". Choosing wrongly makes the object turn the long way around. We will solve this in the next lesson.
This duplication is the only one quaternions have, and it is harmless compared with Euler's: there are no special orientations and no loss of degrees of freedom.
Conversions: matrix and Euler angles
From quaternion to matrix
To draw, the engine ends up needing matrices. Expanding \(q,\mathbf{v},q^*\) for a unit quaternion \((w, x, y, z)\) and collecting what multiplies each component of \(\mathbf{v}\) gives:
\[ R = \begin{pmatrix} 1 - 2(y^2 + z^2) & 2(xy - wz) & 2(xz + wy) \\ 2(xy + wz) & 1 - 2(x^2 + z^2) & 2(yz - wx) \\ 2(xz - wy) & 2(yz + wx) & 1 - 2(x^2 + y^2) \end{pmatrix} \]
Only sums and products: no trigonometric functions at all. Check with \(q_N\) (\(w = 2/\sqrt{5}\), \(y = 1/\sqrt{5}\), \(x = z = 0\)): \(1 - 2y^2 = 1 - 0.4 = 0.6\) at the corners of the diagonal, \(2wy = 0.8\) at the top right, \(-2wy = -0.8\) at the bottom left and 1 in the center. It is \(N\).
It is the Rodrigues matrix of the previous lesson written with the half angle, and it keeps its structure: the terms with \(w\) form the skew-symmetric part.
From matrix to quaternion
Just as when extracting the axis and the angle, the trace and the skew-symmetric part do the work. Adding the diagonal: \(\text{trace}(R) = 3 - 4(x^2 + y^2 + z^2) = 4w^2 - 1\). And subtracting mirror-image entries: \(r_{21} - r_{12} = 4wx\), \(r_{02} - r_{20} = 4wy\), \(r_{10} - r_{01} = 4wz\). Therefore:
\[ w = \frac{\sqrt{1 + \text{trace}(R)}}{2} \qquad x = \frac{r_{21} - r_{12}}{4w} \qquad y = \frac{r_{02} - r_{20}}{4w} \qquad z = \frac{r_{10} - r_{01}}{4w} \]
These formulas divide by \(w\), which is small or zero for rotations close to 180° (the same delicate case as in the previous lesson). The usual solution is to take the largest component as the starting point: if the trace is positive, \(w\) is used; if not, we locate the largest entry on the diagonal, obtain from it the corresponding component \(x\), \(y\) or \(z\), and solve for the others with sums of mirror-image entries (\(r_{10} + r_{01} = 4xy\), and so on).
def quaternion_to_matrix(q):
"""3x3 rotation matrix equivalent to the quaternion q (normalized to be safe)."""
w, x, y, z = quaternion_normalize(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_quaternion(r):
"""Unit quaternion [w, x, y, z] of a 3x3 or 4x4 rotation matrix."""
r = np.asarray(r, dtype=float)[:3, :3]
trace = np.trace(r)
q = [0.0, 0.0, 0.0, 0.0]
if trace > 0.0: # w is large: start from it
w = np.sqrt(1.0 + trace) / 2.0
q = [w, (r[2, 1] - r[1, 2]) / (4 * w), (r[0, 2] - r[2, 0]) / (4 * w), (r[1, 0] - r[0, 1]) / (4 * w)]
else: # start from the largest of x, y, z
a = int(np.argmax(np.diag(r)))
b, c = (a + 1) % 3, (a + 2) % 3
largest = np.sqrt(1.0 + r[a, a] - r[b, b] - r[c, c]) / 2.0
q[0] = (r[c, b] - r[b, c]) / (4 * largest)
q[1 + a] = largest
q[1 + b] = (r[b, a] + r[a, b]) / (4 * largest)
q[1 + c] = (r[c, a] + r[a, c]) / (4 * largest)
return quaternion_normalize(q)
print(np.round(quaternion_to_matrix(q_ship), 6) + 0.0)
print(np.round(matrix_to_quaternion(ship_orientation), 4))
print(np.allclose(quaternion_to_matrix(q_barrel_roll), ship_orientation @ rotation_matrix_z(np.radians(30.0))[:3, :3]))
print(np.allclose(quaternion_to_matrix(-q_ship), quaternion_to_matrix(q_ship)))
half_turn = axis_angle_matrix([0.0, 0.8, 0.6], np.pi)
print(np.round(matrix_to_quaternion(half_turn), 4) + 0.0)The fourth line confirms the double cover (\(q\) and \(-q\) give the same matrix) and the fifth tests the non-positive-trace branch with a half turn about the axis of the tilted orbit: \(w = 0\) and the vector part is the axis itself.
Quaternion and Euler angles
No new formula is needed: it is enough to chain what we already have. With the mini3d convention, \(R = R_y(\psi),R_x(\theta),R_z(\varphi)\), the quaternion is the product of the three basic quaternions in the same order, \(q = q_y(\psi),q_x(\theta),q_z(\varphi)\); or, equivalently, you go through the matrix. To come back, the quaternion is converted to a matrix and the angles are extracted.
yaw, pitch, roll = np.arctan2(0.8, 0.6), np.radians(-30.0), np.radians(20.0)
q_maneuver = matrix_to_quaternion(euler_to_matrix(yaw, pitch, roll))
q_by_product = quaternion_product(
quaternion_product(quaternion_from_axis_angle([0.0, 1.0, 0.0], yaw),
quaternion_from_axis_angle([1.0, 0.0, 0.0], pitch)),
quaternion_from_axis_angle([0.0, 0.0, 1.0], roll))
print(np.round(q_maneuver, 4), np.allclose(q_maneuver, q_by_product))
print(np.round(np.degrees(matrix_to_euler(quaternion_to_matrix(q_maneuver))), 2))This is the division of roles we announced when discussing Euler angles: the maneuver is entered with three readable angles, stored and composed as a quaternion, and displayed again as angles when a person needs to read it. Gimbal lock still exists in that last conversion—it is a problem of the angles—but it no longer contaminates the internal calculations.
Renormalization
Only unit quaternions are rotations. On paper, the product of two unit quaternions is a unit quaternion; on a computer, each product introduces a tiny rounding error, and an object that turns a little every frame accumulates thousands of products. The norm gradually moves away from 1: this is numerical drift. Let's simulate it with single-precision numbers (float32), the usual ones on graphics cards:
step = quaternion_from_axis_angle([0.0, 0.8, 0.6], np.radians(1.0)).astype(np.float32)
q_accumulated = np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32)
for _ in range(100000): # 100,000 one-degree rotations
q_accumulated = quaternion_product(step, q_accumulated).astype(np.float32)
norm_q = float(np.sqrt(np.sum(q_accumulated.astype(float) ** 2)))
print(round(norm_q, 4))
print(round(float(np.sqrt(np.sum(quaternion_normalize(q_accumulated) ** 2))), 6))After a hundred thousand rotations the norm has dropped to 0.999. It looks like very little, but a non-unit quaternion used in \(q,\mathbf{v},q^*\) scales the vector by \(\lVert q \rVert^2\) as well as rotating it: the ship would start to shrink. The remedy is to divide by the norm every so often (every frame, or every certain number of operations): that is what quaternion_normalize does.
Compare it with a matrix. The drift of a rotation matrix spoils its orthogonality: the columns stop being unit vectors and stop being perpendicular, the object gets distorted, and fixing it requires re-orthogonalizing the three columns (for example, rebuilding them with cross products as in orthonormal_basis). A quaternion has only one condition to maintain, and it is restored with a division. It is one of the weightiest reasons for accumulating orientations in quaternions.
Side-by-side comparison of the four representations
| Euler angles | 3×3 matrix | Axis-angle | Unit quaternion | |
|---|---|---|---|---|
| Memory | 3 numbers | 9 numbers | 4 numbers (3 as a rotation vector) | 4 numbers |
| Conditions to maintain | None | 6 (orthogonality) | Unit axis | Norm 1 |
| Composing | Not direct (go through a matrix or quaternion) | Matrix product | Not direct | Hamilton product |
| Inverting | Not direct | Transpose | Change the sign of the angle | Conjugate |
| Rotating a vector | Go through a matrix | Direct and very cheap | Rodrigues (with trigonometry) | \(q,\mathbf{v},q^*\), or go through a matrix if there are many vectors |
| Interpolating | Poor (strange trajectories) | Poor (it stops being a rotation) | Only with a common axis | Very good (nlerp, slerp) |
| Gimbal lock | Yes | No | No | No |
| Uniqueness | Many triples per orientation | Unique | Several (\(\pm\) axis, turns) | Two: \(q\) and \(-q\) |
| Correcting drift | Not applicable | Re-orthogonalize (expensive) | Normalize the axis | Normalize (cheap) |
| Readability | Excellent | Medium (the columns are the axes) | Good | Low |
| Typical use | Interface, editing, simple cameras | Transforming vertices, sending to the GPU | Defining a rotation, angular velocity | Storing, composing and interpolating orientations |
None of them wins at everything, and that is why an engine uses them all: Euler to talk to people, axis-angle to specify rotations, quaternions to store and combine orientations, and matrices to transform the vertices at the end. The conversion functions of this module are the corridors that connect them.
Common Mistakes and Tips
- Mixing up the order of the components.
[w, x, y, z]inmini3d;[x, y, z, w]in many other libraries. A quaternion read in the wrong order is another perfectly valid rotation, so the error does not jump out at you. - Forgetting the half angle. The quaternion of the 90° rotation about Y is \([\cos 45°, 0, \sin 45°, 0]\), not \([\cos 90°, 0, \sin 90°, 0]\) (which is a rotation of 180°).
- Multiplying in the opposite order. \(q_2,q_1\) applies \(q_1\) first. And remember: rotations about world axes, on the left; about the object's own axes, on the right.
- Using non-unit quaternions as rotations. Normalize after building them by hand, after interpolating them or after accumulating many products.
- Comparing quaternions component by component. \(q\) and \(-q\) are the same orientation; compare using the absolute value of their dot product.
- Trying to "read" the components as angles. \(x\), \(y\), \(z\) are not pitch, yaw and roll. The only readable things are that the vector part points along the axis and that \(w\) close to \(\pm 1\) means "almost no rotation".
- Rotating thousands of vertices with \(q,\mathbf{v},q^*\). For many points, convert once to a matrix with
quaternion_to_matrixand multiply. - Tip. Think of a unit quaternion as an axis-angle pair "ready to multiply". Almost any doubt is settled by going back to that picture.
Exercises
Exercise 1. Without a computer: a) write the quaternions of a half turn (180°) of pitch, \(q_x\), and of a half turn of yaw, \(q_y\). b) Compute the quaternion of the maneuver "first the pitch, then the yaw", both about the world axes. c) What rotation is it? d) Does anything change if they are done in the opposite order?
Exercise 2. Rotate by hand, with \(q_N = (2 + j)/\sqrt{5}\), the local point of the ship's sensor, \((2, 1, -3)\), and check that you obtain the known value \(N \cdot \text{sensor} = (-1.2,\ 1,\ -3.4)\).
Exercise 3. The ship, with orientation \(q_N\), raises its nose 90° about its own wing-to-wing axis until it points at the zenith. a) Build the quaternion of the new orientation. b) Check where the nose and the roof point. c) Obtain the axis and the angle of the single rotation that takes the factory orientation to this one. d) What is special about this orientation in Euler angles, and what happens to the quaternion?
Solutions
Solution 1.
a) With \(\theta = 180°\), \(\cos 90° = 0\) and \(\sin 90° = 1\): \(q_x = i = [0, 1, 0, 0]\) and \(q_y = j = [0, 0, 1, 0]\).
b) First the pitch, then the yaw: \(q_y,q_x = j,i = -k = [0, 0, 0, -1]\).
c) \(-k\) and \(k\) represent the same rotation (double cover), and \(k = [\cos 90°, 0, 0, \sin 90°]\) is a half turn about Z. A half turn of pitch followed by a half turn of yaw is equivalent to a half turn of roll. You can check it with one hand: after the first two, the ship points toward \(+Z\) again, but upside down.
d) \(q_x,q_y = i,j = k\). It is a different quaternion (\(k \ne -k\)), but the same rotation. Half turns about perpendicular axes are one of the few cases in which the order does not matter.
Solution 2.
First product, with the scalar-vector formula: \((2,\ (0, 1, 0)) \cdot (0,\ (2, 1, -3))\).
- Scalar: \(0 - (0, 1, 0) \cdot (2, 1, -3) = -1\).
- Vector: \(2,(2, 1, -3) + \mathbf{0} + (0, 1, 0) \times (2, 1, -3) = (4, 2, -6) + (-3, 0, -2) = (1, 2, -8)\).
Second product: \((-1,\ (1, 2, -8)) \cdot (2,\ (0, -1, 0))\).
- Scalar: \(-2 - (1, 2, -8) \cdot (0, -1, 0) = -2 + 2 = 0\) ✓ (pure).
- Vector: \(-1,(0, -1, 0) + 2,(1, 2, -8) + (1, 2, -8) \times (0, -1, 0) = (0, 1, 0) + (2, 4, -16) + (-8, 0, -1) = (-6, 5, -17)\).
Dividing by 5: \((-1.2,\ 1,\ -3.4)\) ✓.
Solution 3.
a) Raising the nose is a negative pitch, and it is done about one of the ship's own axes: we multiply on the right. \(q = q_N,q_x(-90°)\).
q_zenith = quaternion_product(q_ship, quaternion_from_axis_angle([1.0, 0.0, 0.0], np.radians(-90.0)))
print(np.round(q_zenith, 4))
print(np.round(rotate_with_quaternion(q_zenith, [0.0, 0.0, 1.0]), 4) + 0.0,
np.round(rotate_with_quaternion(q_zenith, [0.0, 1.0, 0.0]), 4) + 0.0)
axis, angle = matrix_to_axis_angle(quaternion_to_matrix(q_zenith))
print(np.round(axis, 4), round(np.degrees(angle), 2))
print(np.round(np.degrees(matrix_to_euler(quaternion_to_matrix(q_zenith))), 2) + 0.0)[ 0.6325 -0.6325 0.3162 0.3162] [0. 1. 0.] [-0.8 0. -0.6] [-0.8165 0.4082 0.4082] 101.54 [ 53.13 -90. 0. ]
b) The nose points at \((0, 1, 0)\), the zenith, and the roof at \((-0.8, 0, -0.6) = -n_3\): it faces where the tail used to be.
c) A single rotation of 101.54° about \((-0.8165, 0.4082, 0.4082)\), that is, \((-2, 1, 1)/\sqrt{6}\). It can also be read directly from the quaternion: \(2\arccos(0.6325) \approx 101.54°\), and the vector part is proportional to \((-2, 1, 1)\).
d) The pitch is \(-90°\): it is the gimbal lock orientation, where yaw and roll become indistinguishable. The quaternion, on the other hand, has nothing special about it: four ordinary numbers of norm 1, which can go on being composed with any other rotation without losing any degree of freedom.
Conclusion
A quaternion is a number with four components, \(w + xi + yj + zk\), with a product—Hamilton's—that combines the dot product and the cross product and is not commutative. Unit quaternions represent rotations: \(q = (\cos\frac{\theta}{2},\ \sin\frac{\theta}{2},\mathbf{k})\) stores an axis and an angle; \(q,\mathbf{v},q^*\) rotates a vector (the quaternion acts from both sides, hence the half angle); the product \(q_2,q_1\) composes rotations in the same order as matrices; the conjugate inverts, and normalizing corrects the drift. There is no gimbal lock, and the only duplication is that \(q\) and \(-q\) are the same rotation. With the conversions to a matrix and to Euler angles, mini3d can use each representation where it performs best. One virtue remains to be exploited, the one that has contributed most to the fame of quaternions: since they are points on a sphere, you can go from one to another along the shortest path. In the next lesson, "Interpolating Rotations: Lerp, Nlerp and Slerp", we will make the ship turn smoothly from one orientation to another.
