Rotations: Matrices vs Quaternions
A 3D rotation can be stored as a orthogonal matrix, as three Euler angles, or as a unit quaternion. Matrices are best for transforming many points, Euler angles are easiest for people to type, and quaternions are best for composing and interpolating rotations. This lesson shows why with code, including gimbal lock and slerp.
Three representations
| Representation | Numbers | Strength | Weakness |
|---|---|---|---|
| Rotation matrix (, ) | 9 | transforms vectors with one product; GPU-native | drifts away from orthogonal; awkward to interpolate |
| Euler angles (yaw, pitch, roll) | 3 | human-friendly | order-dependent; gimbal lock |
| Unit quaternion | 4 | compact, cheap to compose, smooth interpolation (slerp) | less intuitive; and are the same rotation |
All three describe the same group of orthogonal matrices with determinant 1. Game-engine details are in Euler Angles, Axis-Angle and Quaternions.
Gimbal lock
Build a rotation from Euler angles as . When , the roll axis is turned onto the yaw axis, and the two angles do the same thing: only their difference matters. One degree of freedom is lost, which is gimbal lock. The matrix is still a perfectly good rotation; the problem is the parametrization.
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 euler(yaw, pitch, roll):
return Ry(np.radians(yaw)) @ Rx(np.radians(pitch)) @ Rz(np.radians(roll))
A = euler(30, 90, 10)
B = euler(50, 90, 30) # yaw and roll both +20°: same difference
print("same matrix at pitch 90:", np.allclose(A, B))
print("same matrix at pitch 80:", np.allclose(euler(30, 80, 10), euler(50, 80, 30)))
# Near the lock, a small change of the actual rotation needs a huge change in the angles
J = np.zeros((9, 3))
for i in range(3):
d = np.zeros(3); d[i] = 1e-6
J[:, i] = (euler(*(np.array([30, 89.9, 10]) + d)) - euler(30, 89.9, 10)).ravel() / 1e-6
sv = np.linalg.svd(J)[1] * 180 / np.pi # per radian instead of per degree
print("singular values of d(matrix)/d(angles) at pitch 89.9:", [round(float(x), 4) for x in sv])same matrix at pitch 90: True
same matrix at pitch 80: False
singular values of d(matrix)/d(angles) at pitch 89.9: [2.0, 1.4142, 0.0017]
One singular value of the derivative map is almost zero near pitch 90°: some angle change barely moves the rotation, so the reverse direction (finding angles for a desired small rotation) blows up. That is the matrix-calculus signature of gimbal lock, and the SVD is the tool that reveals it.
Quaternions in one page
A quaternion is with . Multiplication is associative but not commutative ( but ). A rotation by angle about the unit axis is the unit quaternion
and a vector (as the pure quaternion ) is rotated by , where is the conjugate. Composition is multiplication: means "first , then ", like the matrix product . Because appears, and give the same rotation (a double cover).
Every unit quaternion corresponds to a rotation matrix:
import numpy as np
def qmul(a, b):
w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
def axis_angle(axis, deg):
n = np.asarray(axis, float) / np.linalg.norm(axis); h = np.radians(deg) / 2
return np.concatenate([[np.cos(h)], np.sin(h) * n])
def rotate(q, v):
conj = q * np.array([1, -1, -1, -1])
return qmul(qmul(q, np.concatenate([[0.0], v])), conj)[1:]
def 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)]])
qz = axis_angle([0, 0, 1], 90)
qx = axis_angle([1, 0, 0], 90)
v = np.array([1.0, 0.0, 0.0])
print("rotate x-axis 90° about z:", np.round(rotate(qz, v), 6) + 0)
q = qmul(qx, qz) # first z, then x
print("first z then x:", np.round(rotate(q, v), 6) + 0)
R = to_matrix(qx) @ to_matrix(qz)
print("matrix product agrees:", np.allclose(to_matrix(q), R), " det =", round(float(np.linalg.det(R)), 6))
print("qx qz == qz qx ?", np.allclose(qmul(qx, qz), qmul(qz, qx)))rotate x-axis 90° about z: [0. 1. 0.]
first z then x: [0. 0. 1.]
matrix product agrees: True det = 1.0
qx qz == qz qx ? False
Interpolation: slerp
To blend smoothly between two orientations (animation, camera moves, network smoothing), linearly interpolating matrices fails: is generally not orthogonal, so it shrinks and skews the model. Slerp (spherical linear interpolation) moves along the great circle between two unit quaternions at constant angular speed:
If , negate first so the blend takes the short way round. See Slerp.
import numpy as np
def 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 slerp(q0, q1, t):
d = float(q0 @ q1)
if d < 0: q1, d = -q1, -d
om = np.arccos(min(d, 1.0))
return (np.sin((1 - t) * om) * q0 + np.sin(t * om) * q1) / np.sin(om)
q0 = np.array([1.0, 0, 0, 0]) # identity
q1 = np.array([np.cos(np.radians(80)), 0, 0, np.sin(np.radians(80))]) # 160° about z
R0, R1 = to_matrix(q0), to_matrix(q1)
for t in (0.25, 0.5, 0.75):
L = (1 - t) * R0 + t * R1
S = to_matrix(slerp(q0, q1, t))
ang = np.degrees(np.arctan2(S[1, 0], S[0, 0]))
print(f"t={t}: lerped matrix det={np.linalg.det(L):.4f} |L e1|={np.linalg.norm(L[:, 0]):.4f} "
f"slerp det={np.linalg.det(S):.4f} angle={ang:.1f}°")t=0.25: lerped matrix det=0.2726 |L e1|=0.5221 slerp det=1.0000 angle=40.0°
t=0.5: lerped matrix det=0.0302 |L e1|=0.1736 slerp det=1.0000 angle=80.0°
t=0.75: lerped matrix det=0.2726 |L e1|=0.5221 slerp det=1.0000 angle=120.0°
Halfway between the identity and a 160° turn, the lerped matrix has squashed the model to almost nothing (), while slerp gives a clean 80° rotation.
Costs and practice
| Task | Matrix | Quaternion |
|---|---|---|
| storage | 9 floats | 4 floats |
| compose two rotations | 27 multiplies | 16 multiplies |
| rotate one vector | 9 multiplies | about 15 (or convert to a matrix once) |
| fix numerical drift | re-orthonormalize (Gram-Schmidt) | divide by its length |
| interpolate | not directly | slerp / nlerp |
So engines store orientations as quaternions (Unity's Quaternion, Unreal's FQuat, Three.js Quaternion), expose Euler angles in the editor, and convert to a matrix when it is time to render.
Exercises
Exercise 1: Quaternion for a turn
Write the unit quaternion for a 180° rotation about the -axis.
Answer
(and is the same rotation).
Solution
and , so in order.
Exercise 2: Lost degree of freedom
With and , which other Euler triple gives the same matrix as ?
Answer
Any , for example or .
Solution
Conjugating a rotation moves its axis: is the rotation by about , which is . So
Only matters, so adding the same to both angles gives the same matrix, exactly what the lesson's code found.
Exercise 3: Double cover
Show that and rotate every vector the same way.
Answer
.
Solution
Conjugation is linear, so , and the two minus signs cancel: .
Exercise 4: Slerp halfway (code)
Slerp halfway between a 0° and a 90° rotation about , and check that the result rotates to .
Answer
, which maps to .
Solution
The angle between the quaternions is (half of 90°), so the halfway quaternion is at 22.5° on the great circle, a 45° rotation.
import numpy as np
q0 = np.array([1.0, 0, 0, 0]); q1 = np.array([np.cos(np.pi / 4), np.sin(np.pi / 4), 0, 0])
om = np.arccos(q0 @ q1)
q = (np.sin(0.5 * om) * q0 + np.sin(0.5 * om) * q1) / np.sin(om)
w, x = q[0], q[1]
Rx = np.array([[1, 0, 0], [0, 1 - 2*x*x, -2*w*x], [0, 2*w*x, 1 - 2*x*x]])
print(np.round(q, 4), np.round(Rx @ [0, 1, 0], 4))[0.9239 0.3827 0. 0. ] [0. 0.7071 0.7071]
Test yourself
What is gimbal lock?
- A rotation matrix with determinant 0
- Losing one degree of freedom in an Euler-angle parametrization when two axes line up
- A bug in quaternion multiplication
- The double cover
Why is linearly interpolating two rotation matrices a bad idea?
- It is too slow
- The result is generally not orthogonal, so it scales and skews
- It always gives the identity
- Matrices cannot be added
A unit quaternion for a rotation of about axis has scalar part…