We know how to represent an orientation in four ways and how to go from one to another. What is missing is the operation that brings a scene to life: going smoothly from one orientation to another. The ship cannot go from staring into the void to looking at the lighthouse in a single frame; it has to turn little by little, and every intermediate position has to be a valid orientation, with no distortions or detours. For positions we solved this problem in the first lesson of the course, with linear interpolation. For orientations it is trickier, because they do not live in a "flat" space where a straight line can be drawn between two of them. In this lesson we will see why the naive attempts fail and study the three techniques used with quaternions—lerp, nlerp and slerp—with their costs and their guarantees, and we will finish by interpolating a complete pose and limiting the ship's turning speed.

The code assumes that lerp (from "Vectors and Vector Spaces"), displacement, orthonormal_basis, the quaternion functions from the previous lesson (quaternion_from_axis_angle, quaternion_product, quaternion_normalize, rotate_with_quaternion, quaternion_to_matrix, matrix_to_quaternion), matrix_to_euler, model_matrix and the matrix ship_orientation are already defined.

The problem: from one orientation to another

Interpolating means manufacturing the intermediate states between two known states, governed by a parameter \(t\) that goes from 0 (the initial state) to 1 (the final one). For two points \(A\) and \(B\) we have been using, since the start of the course,

\[ \text{lerp}(A, B, t) = (1 - t),A + t,B \]

which travels along the segment between them at a uniform pace. We want the same for orientations: a function that, given \(q_0\) and \(q_1\), returns the intermediate orientation for each \(t\). We ask three things of a good interpolation of orientations:

  1. That every intermediate result is a valid rotation (with no scaling or distortion).
  2. That it follows the shortest path: a single turn about a fixed axis, with no detours.
  3. That it advances at constant angular velocity: equal increments of \(t\) give equal increments of angle.

The uses are constant in a game: a turret aiming at its target, a camera repositioning itself, the blend of two poses of a character. In this lesson we build the mathematical tool; how the parameter \(t\) is managed over time (keyframes, easing curves) belongs to the lesson "3D Animation".

The lesson's example. The ship leaves \((8, 3, 6)\) with its orientation \(N\) and, following its velocity \((2, 0, -1)\), two seconds later it is at \((12, 3, 4)\). We want it to reach that point looking toward the lighthouse. From there, the direction to the base of the lighthouse is \((-12, -3, -4)\), of norm 13, and orthonormal_basis gives us the corresponding orientation:

import numpy as np

ship = np.array([8.0, 3.0, 6.0])
lighthouse = np.array([0.0, 0.0, 0.0])
arrival = np.array([12.0, 3.0, 4.0])

lighthouse_orientation = orthonormal_basis(displacement(arrival, lighthouse))
q_start = matrix_to_quaternion(ship_orientation)
q_lighthouse = matrix_to_quaternion(lighthouse_orientation)

print(np.round(lighthouse_orientation, 4))
print(np.round(np.degrees(matrix_to_euler(lighthouse_orientation)), 2) + 0.0)
print(np.round(q_start, 4), np.round(q_lighthouse, 4))
[[-0.3162 -0.2189 -0.9231]
 [ 0.      0.973  -0.2308]
 [ 0.9487 -0.073  -0.3077]]
[-108.43   13.34    0.  ]
[0.8944 0.     0.4472 0.    ] [ 0.5808  0.0679 -0.8057  0.0942]

The final orientation has a yaw of \(-108.43°\) and a pitch of \(13.34°\) (nose slightly down); the initial one, a yaw of \(53.13°\). It is a large rotation, of more than 160°: a good test bench.

Why interpolating matrices or Euler angles does not work

Matrices, entry by entry

The most direct idea is to apply lerp to the two orientation matrices. Let's see what comes out halfway:

halfway = lerp(ship_orientation, lighthouse_orientation, 0.5)
print(np.round(halfway, 4))
print(np.round(halfway.T @ halfway, 4))
print(round(float(np.linalg.det(halfway)), 4),
      np.round([np.linalg.norm(halfway[:, c]) for c in range(3)], 4))
[[ 0.1419 -0.1095 -0.0615]
 [ 0.      0.9865 -0.1154]
 [ 0.0743 -0.0365  0.1462]]
[[ 0.0257 -0.0182  0.0021]
 [-0.0182  0.9865 -0.1124]
 [ 0.0021 -0.1124  0.0385]]
0.0253 [0.1602 0.9932 0.1961]

The intermediate matrix is not a rotation. \(M^T M\) should be the identity and looks nothing like it; the determinant is 0.025 instead of 1, and the columns—the ship's axes—measure 0.16, 0.99 and 0.20 instead of 1. If we drew the ship with that matrix, halfway through the maneuver it would appear squashed to a sixth of its width and a fifth of its length, only to swell back up at the end. The reason is geometric: each column travels in a straight line between its initial and final positions, and the straight line joining two points of a sphere passes through its interior. The larger the rotation, the closer to the center it passes. The average of two orthogonal matrices is not, in general, orthogonal.

Euler angles, component by component

Interpolating yaw, pitch and roll separately does always produce valid rotations (any triple is one), so it meets the first requirement. It fails on the other two, as we saw in "Euler Angles and Gimbal Lock":

  • The path is not the shortest: there the nose traveled 31.26° to bridge a separation of 20°, going around the vertical.
  • There are wrap-around jumps: from 170° to \(-170°\) it sweeps 340° instead of 20°.
  • The result depends on the axis convention chosen, and near gimbal lock the angles change abruptly.
  • The actual angular velocity is not constant, even though each angle advances uniformly.

We need a representation in which "going in a straight line" makes sense. Quaternions provide it.

Unit quaternions live on a sphere

A unit quaternion is four numbers with \(w^2 + x^2 + y^2 + z^2 = 1\). Just as the unit vectors of 3D are the points of a sphere of radius 1, unit quaternions are the points of the unit sphere of four-dimensional space. There is no need to visualize it: it is enough to reason by analogy with an ordinary sphere, or even with a circle, because everything we will do happens in the plane that contains the two quaternions and the origin.

Between two points of a sphere we can measure an angle with the dot product (the four-component one):

\[ \cos\Omega = q_0 \cdot q_1 = w_0 w_1 + x_0 x_1 + y_0 y_1 + z_0 z_1 \]

This angle \(\Omega\) has a precise meaning. The dot product \(q_0 \cdot q_1\) coincides with the scalar part of the quaternion \(q_1,q_0^*\), which is the rotation that takes the orientation \(q_0\) to \(q_1\); and the scalar part of a quaternion is the cosine of half its angle of rotation. Therefore:

The angle \(\Omega\) between two quaternions on the sphere is half the angle of the rotation that separates the two orientations.

In our example, \(q_0 \cdot q_1 = 0.8944 \cdot 0.5808 + 0.4472 \cdot (-0.8057) \approx 0.1591\), so \(\Omega \approx 80.85°\) and the two orientations are separated by a rotation of \(2,\Omega \approx 161.69°\).

On the sphere, the shortest path between two points is the great-circle arc that joins them (like the routes of airplanes over the Earth). Traveling along that arc is equivalent, in terms of rotations, to turning about a fixed axis: exactly requirement 2. The three techniques that follow differ in how they approach that arc.

Lerp: the chord that cuts through the sphere

The first thing to try is the usual linear interpolation, component by component, on the four numbers:

\[ \text{lerp}(q_0, q_1, t) = (1 - t),q_0 + t,q_1 \]

def quaternion_lerp(q0, q1, t):
    """Component-by-component linear interpolation. The result is NOT a unit quaternion."""
    return lerp(np.asarray(q0, dtype=float), np.asarray(q1, dtype=float), t)

for t in (0.0, 0.25, 0.5, 0.75, 1.0):
    q = quaternion_lerp(q_start, q_lighthouse, t)
    print(t, np.round(q, 4), round(float(np.sqrt(np.sum(q * q))), 4))
0.0 [0.8944 0.     0.4472 0.    ] 1.0
0.25 [0.816  0.017  0.134  0.0236] 0.8274
0.5 [ 0.7376  0.034  -0.1793  0.0471] 0.7613
0.75 [ 0.6592  0.0509 -0.4925  0.0707] 0.8274
1.0 [ 0.5808  0.0679 -0.8057  0.0942] 1.0

We reuse lerp as it is. The last column is the norm: it is 1 at the ends and drops to 0.7613 in the middle. It is the same phenomenon as with the matrices: lerp travels along the chord, the straight segment that joins the two points through the interior of the sphere. (The minimum is \(\cos\frac{\Omega}{2} = \cos 40.42° \approx 0.7613\), the distance from the center to the midpoint of the chord.)

A quaternion that is not a unit quaternion is not a rotation: used in \(q,\mathbf{v},q^*\) it would shrink the ship. So lerp, as it stands, will not do. But the difference from the case of the matrices is enormous: there six conditions were broken and repairing them was expensive; here only one has been broken, the norm, and we know how to fix it with a division.

Nlerp: lerp and normalize

Normalized linear interpolation (nlerp) consists of doing a lerp and normalizing the result:

\[ \text{nlerp}(q_0, q_1, t) = \frac{(1 - t),q_0 + t,q_1}{\lVert (1 - t),q_0 + t,q_1 \rVert} \]

Geometrically, normalizing means projecting each point of the chord onto the sphere, along the radius that passes through it. And since the chord and the arc lie in the same plane (the one defined by \(q_0\), \(q_1\) and the origin), the projection of the chord falls exactly on the great-circle arc. That is:

  • nlerp follows the correct path: the same points as the best possible interpolation. It meets requirements 1 and 2.
  • But it does not travel along it at constant speed. A point advancing uniformly along the chord, seen from the center, sweeps little angle near the ends (where the chord is seen "at a glancing angle") and a lot in the central region (where it is seen head-on). The rotation starts slowly, speeds up in the middle and slows down at the end.
def quaternion_nlerp(q0, q1, t):
    """Normalized linear interpolation: correct path, non-constant speed."""
    q0 = np.asarray(q0, dtype=float)
    q1 = np.asarray(q1, dtype=float)
    if np.sum(q0 * q1) < 0.0:                    # shortest path (explained further down)
        q1 = -q1
    return quaternion_normalize(quaternion_lerp(q0, q1, t))

def angle_between_orientations(q0, q1):
    """Angle (radians, between 0 and pi) of the rotation that separates two orientations."""
    cosine = min(1.0, abs(float(np.sum(np.asarray(q0) * np.asarray(q1)))))
    return 2.0 * np.arccos(cosine)

print(round(np.degrees(angle_between_orientations(q_start, q_lighthouse)), 2))
for t in (0.25, 0.5, 0.75):
    q = quaternion_nlerp(q_start, q_lighthouse, t)
    print(t, np.round(q, 4), round(np.degrees(angle_between_orientations(q_start, q)), 2))
161.69
0.25 [0.9862 0.0205 0.1619 0.0285] 34.71
0.5 [ 0.9689  0.0446 -0.2355  0.0619] 80.85
0.75 [ 0.7966  0.0616 -0.5952  0.0854] 126.98

The helper function angle_between_orientations applies the boxed statement of the previous section: twice the angle between the quaternions (the absolute value takes care of the double cover). With it we measure how far the ship has turned at each instant. At constant speed, a quarter of the way through it should have turned \(161.69° / 4 = 40.42°\); with nlerp it has only done 34.71°. In the middle it is spot on by symmetry (80.85°), and at three quarters it is ahead (126.98° versus 121.27°).

Is that serious? It depends on the size of the rotation. The lag grows very quickly with the total angle: it is a few hundredths of a degree for rotations of 30°, less than 1° for rotations of 90° and almost 6° in our 162° example. For small rotations—and between two consecutive frames almost all of them are—nlerp is practically indistinguishable from perfect interpolation, and it costs a fraction as much.

Slerp: spherical interpolation

The geometric idea

Slerp (spherical linear interpolation) travels along the same great-circle arc as nlerp, but at uniform speed: the point corresponding to \(t\) is the one that has covered the fraction \(t\) of the angle \(\Omega\). It therefore meets all three requirements: valid rotation, shortest path and constant angular velocity.

Deriving the formula

We are looking for the point of the arc that makes an angle \(t,\Omega\) with \(q_0\). The problem is planar, and we solve it as we did when deriving Rodrigues' formula: by building two perpendicular axes in the plane of the arc.

  • The first axis is \(q_0\).
  • The second, \(q_\perp\), is the part of \(q_1\) perpendicular to \(q_0\), normalized. The projection of \(q_1\) onto \(q_0\) is \(\cos\Omega\ q_0\); what is left, \(q_1 - \cos\Omega\ q_0\), has length \(\sin\Omega\). So:

\[ q_\perp = \frac{q_1 - \cos\Omega\ q_0}{\sin\Omega} \]

With two perpendicular unit axes, the point of the circle located at an angle \(t,\Omega\) from the first is, as always, "cosine along the first axis, sine along the second":

\[ q(t) = \cos(t,\Omega)\ q_0 + \sin(t,\Omega)\ q_\perp \]

All that remains is to substitute \(q_\perp\) and collect what multiplies \(q_0\):

\[ q(t) = \frac{\sin\Omega,\cos(t,\Omega) - \cos\Omega,\sin(t,\Omega)}{\sin\Omega}\ q_0 + \frac{\sin(t,\Omega)}{\sin\Omega}\ q_1 \]

The numerator of the first term is the sine of a difference, \(\sin(\Omega - t,\Omega)\). We are left with the slerp formula:

\[ \boxed{\ \text{slerp}(q_0, q_1, t) = \frac{\sin\big((1 - t),\Omega\big)}{\sin\Omega}\ q_0 + \frac{\sin(t,\Omega)}{\sin\Omega}\ q_1 \qquad \cos\Omega = q_0 \cdot q_1\ } \]

It has the same form as lerp—a combination of \(q_0\) and \(q_1\) with two weights—but the weights are no longer \(1 - t\) and \(t\), but quotients of sines. Checks: with \(t = 0\) the weights are 1 and 0; with \(t = 1\), 0 and 1. And the result is a unit quaternion with no need to normalize, because by construction it lies on the circle.

The constant speed can be read from the intermediate form: \(q(t)\) makes an angle \(t,\Omega\) with \(q_0\) on the sphere, so the orientation has turned \(2,t,\Omega\), an amount proportional to \(t\).

Example by hand

The lighthouse lamp rotates about the vertical. Let's interpolate between \(\beta = 0°\) and \(\beta = 90°\), with \(t = \frac{1}{3}\). We expect, naturally, \(\beta = 30°\).

  • \(q_0 = [1, 0, 0, 0]\) and \(q_1 = [\cos 45°, 0, \sin 45°, 0] = [0.7071,\ 0,\ 0.7071,\ 0]\).
  • \(\cos\Omega = q_0 \cdot q_1 = 0.7071\), so \(\Omega = 45°\) (half of 90°).
  • Weights: \(\frac{\sin 30°}{\sin 45°} = \frac{0.5}{0.7071} = 0.7071\) and \(\frac{\sin 15°}{\sin 45°} = \frac{0.2588}{0.7071} = 0.3660\).
  • \(q = 0.7071,[1, 0, 0, 0] + 0.3660,[0.7071, 0, 0.7071, 0] = [0.9659,\ 0,\ 0.2588,\ 0]\).

And \([0.9659, 0, 0.2588, 0] = [\cos 15°, 0, \sin 15°, 0]\): a rotation of 30° about Y. Exact. With nlerp we would have obtained \([0.9024, 0, 0.2357, 0]\) normalized, that is, \([0.9675, 0, 0.2527, 0]\): a rotation of 29.28°, slightly behind.

The code

def quaternion_slerp(q0, q1, t, threshold=0.9995):
    """Spherical interpolation: shortest path at constant angular velocity."""
    q0 = np.asarray(q0, dtype=float)
    q1 = np.asarray(q1, dtype=float)
    cosine = float(np.sum(q0 * q1))
    if cosine < 0.0:                             # shortest path
        q1, cosine = -q1, -cosine
    if cosine > threshold:                       # very small angle: nlerp
        return quaternion_normalize(quaternion_lerp(q0, q1, t))
    omega = np.arccos(cosine)
    weight0 = np.sin((1.0 - t) * omega) / np.sin(omega)
    weight1 = np.sin(t * omega) / np.sin(omega)
    return weight0 * q0 + weight1 * q1

for t in (0.0, 0.25, 0.5, 0.75, 1.0):
    q = quaternion_slerp(q_start, q_lighthouse, t)
    print(t, np.round(q, 4), round(np.degrees(angle_between_orientations(q_start, q)), 2),
          np.round(rotate_with_quaternion(q, [0.0, 0.0, 1.0]), 4))
0.0 [0.8944 0.     0.4472 0.    ] 0.0 [0.8 0.  0.6]
0.25 [0.9928 0.0238 0.1128 0.033 ] 40.42 [ 0.2256 -0.0398  0.9734]
0.5 [ 0.9689  0.0446 -0.2355  0.0619] 80.85 [-0.4508 -0.1156  0.8851]
0.75 [ 0.8257  0.06   -0.5548  0.0832] 121.27 [-0.9061 -0.1913  0.3773]
1.0 [ 0.5808  0.0679 -0.8057  0.0942] 161.69 [-0.9231 -0.2308 -0.3077]

The central lines of the function are the boxed formula; the two checks before them are explained in the next two sections. In the output, the third column is the angle turned: 40.42°, 80.85°, 121.27°, 161.69°, exactly proportional to \(t\). The fourth is the ship's nose, which goes from \(n_3 = (0.8, 0, 0.6)\) to \((-12, -3, -4)/13\), sweeping across the horizon while dropping little by little. Halfway through, slerp and nlerp coincide.

The shortest path

Let's recall the double cover: \(q_1\) and \(-q_1\) are the same orientation. But on the sphere they are opposite points, and the arcs from \(q_0\) to one and to the other are different journeys: if one measures \(\Omega\), the other measures \(180° - \Omega\). In terms of rotation, one is the turn through an angle \(\theta\) and the other the turn through \(360° - \theta\) in the opposite direction: both reach the same orientation, one by the shortest path and the other going almost all the way around.

The rule for choosing is immediate: the short arc is the one that measures less than 90° on the sphere, that is, the one whose cosine is positive.

If \(q_0 \cdot q_1 < 0\), replace \(q_1\) by \(-q_1\) before interpolating.

These are the lines marked "shortest path" in quaternion_nlerp and quaternion_slerp. Let's see their effect with the lighthouse lamp, which must go from \(\beta = 10°\) to \(\beta = 350°\): two orientations only 20° apart (passing through 0°).

q_10 = quaternion_from_axis_angle([0.0, 1.0, 0.0], np.radians(10.0))
q_350 = quaternion_from_axis_angle([0.0, 1.0, 0.0], np.radians(350.0))
print(np.round(q_10, 4), np.round(q_350, 4), round(float(np.sum(q_10 * q_350)), 4))

print(np.round(quaternion_slerp(q_10, q_350, 0.5), 4) + 0.0)                  # with the correction
print(np.round(quaternion_normalize(quaternion_lerp(q_10, q_350, 0.5)), 4) + 0.0)   # without it
[0.9962 0.     0.0872 0.    ] [-0.9962  0.      0.0872  0.    ] -0.9848
[1. 0. 0. 0.]
[0. 0. 1. 0.]

The dot product is negative. With the correction, the midpoint is \([1, 0, 0, 0]\), the identity: \(\beta = 0°\), halfway through the short 20° rotation. Without it, the midpoint is \([0, 0, 1, 0]\), a yaw of 180°: the lamp would have gone around the long way, 340°.

A borderline case: if \(q_0 \cdot q_1 = 0\), the orientations are exactly 180° apart and the two paths are the same length. The interpolation still works, but the direction of rotation is decided by rounding. This is what would happen if the ship wanted to look at the lighthouse from its initial position, \((8, 3, 6)\): since the lighthouse is dead astern, the rotation is exactly a half turn and there is no "short side". (That is why the lesson's example uses the arrival position.) In a game, that tie is broken with a rule of its own: for example, always turning toward the side of the last movement.

Small angles

The slerp formula divides by \(\sin\Omega\). When the two orientations are almost equal, \(\Omega \approx 0\), and one tiny number is divided by another: the result is dominated by rounding errors, and with \(\Omega = 0\) exactly it is a division by zero.

The solution takes advantage of what we already know: for small angles nlerp and slerp are indistinguishable (the chord and the arc practically coincide). That is why quaternion_slerp checks whether the cosine exceeds a threshold close to 1 and, in that case, falls back on nlerp. With the threshold 0.9995, the switch happens when the orientations are less than about 3.6° apart, where the difference between the two methods is negligible.

q_a = quaternion_from_axis_angle([0.0, 1.0, 0.0], np.radians(10.0))
q_b = quaternion_from_axis_angle([0.0, 1.0, 0.0], np.radians(10.5))
print(round(float(np.sum(q_a * q_b)), 6))
print(np.round(quaternion_slerp(q_a, q_b, 0.5), 6))
print(np.round(quaternion_from_axis_angle([0.0, 1.0, 0.0], np.radians(10.25)), 6))
print(np.round(quaternion_slerp(q_a, q_a, 0.5), 6))
0.99999
[0.996002 0.       0.089329 0.      ]
[0.996002 0.       0.089329 0.      ]
[0.996195 0.       0.087156 0.      ]

Between yaws of 10° and 10.5° the function uses the nlerp branch and returns, to the sixth decimal place, the exact quaternion for 10.25°. And with two identical orientations (last line) there is no division by zero.

Side-by-side comparison: lerp, nlerp and slerp

Lerp Nlerp Slerp
Formula \((1 - t),q_0 + t,q_1\) Lerp and normalize Weights \(\frac{\sin((1 - t)\Omega)}{\sin\Omega}\) and \(\frac{\sin(t,\Omega)}{\sin\Omega}\)
Unit result No Yes Yes
Path Chord (through the inside of the sphere) Great-circle arc Great-circle arc
Constant angular velocity No No (slow at the ends, fast in the middle) Yes
Cost 8 products Lerp plus a square root and a division One arccos and three sines, on top of the products
Commutative when blending several Yes Yes No
Delicate cases — Opposite orientations (zero sum) \(\Omega \approx 0\) (it falls back on nlerp)
When to use it Never on its own: it is the step before nlerp Small rotations; blending many orientations every frame Large rotations; when the pace of the rotation must be exact

The commutativity row refers to blending more than two orientations (for example, combining three poses with weights). With lerp and nlerp this is a weighted sum, and it makes no difference in what order the terms are accumulated. With slerp you have to chain interpolations two at a time, and the result depends on the order chosen. This property, together with its low cost, explains why many engines use nlerp for almost everything and reserve slerp for wide rotations. In all three the shortest-path rule has to be applied first.

Interpolating a complete pose

The pose of a rigid object is its position plus its orientation. Interpolating 4×4 model matrices entry by entry would have the same flaw we saw at the beginning (the rotation block degrades), so the pose is interpolated in parts, each with its own tool:

  • the position, with the linear interpolation of points;
  • the orientation, with slerp (or nlerp);
  • the scale, if there is one, with another linear interpolation.

With the result the model matrix is assembled as always, \(T \cdot R \cdot S\).

def lerp_pose(position0, q0, position1, q1, t):
    """Intermediate pose: position by linear interpolation and orientation by slerp."""
    position = lerp(np.asarray(position0, dtype=float), np.asarray(position1, dtype=float), t)
    return position, quaternion_slerp(q0, q1, t)

for t in (0.0, 0.5, 1.0):
    position, q = lerp_pose(ship, q_start, arrival, q_lighthouse, t)
    print(t, position, np.round(q, 4))

position, q = lerp_pose(ship, q_start, arrival, q_lighthouse, 0.5)
model = model_matrix(position, quaternion_to_matrix(q))
print(np.round(model, 4))
0.0 [8. 3. 6.] [0.8944 0.     0.4472 0.    ]
0.5 [10.  3.  5.] [ 0.9689  0.0446 -0.2355  0.0619]
1.0 [12.  3.  4.] [ 0.5808  0.0679 -0.8057  0.0942]
[[ 0.8814 -0.141  -0.4508 10.    ]
 [ 0.0989  0.9884 -0.1156  3.    ]
 [ 0.4618  0.0573  0.8851  5.    ]
 [ 0.      0.      0.      1.    ]]

Halfway through the maneuver the ship is at \((10, 3, 5)\) and its orientation is the middle quaternion of the slerp table. The model matrix is built at the end, just once, from the position and the quaternion converted to a matrix: it is the usual division of roles (interpolate with quaternions, draw with matrices).

Turning with a maximum angular velocity

Often the duration of the rotation is not known in advance: the target moves, and what we want is for the ship to turn toward it without exceeding a certain angular velocity, for example 45° per second. It is the angular equivalent of move_toward, which in "Vectors in 3D Space" advanced toward a target without overshooting it. The recipe is the same:

  1. Measure the remaining angle, \(\theta\), between the current orientation and the desired one.
  2. Compute the maximum rotation allowed in this frame: \(\theta_{\max} = \text{angular velocity} \times \Delta t\).
  3. If \(\theta \le \theta_{\max}\), adopt the desired orientation directly. Otherwise, advance with slerp by the fraction \(t = \theta_{\max} / \theta\).

Here the constant speed of slerp is essential: the fraction \(t\) translates exactly into the angle \(\theta_{\max}\).

def rotate_toward(q_current, q_target, max_angle):
    """Rotate from q_current toward q_target by at most `max_angle` radians."""
    angle = angle_between_orientations(q_current, q_target)
    if angle <= max_angle:
        return np.asarray(q_target, dtype=float).copy()
    return quaternion_slerp(q_current, q_target, max_angle / angle)

angular_velocity = np.radians(45.0)              # per second
dt = 0.5                                         # half a second per step
q = q_start.copy()
step = 0
while angle_between_orientations(q, q_lighthouse) > 1e-9:
    q = rotate_toward(q, q_lighthouse, angular_velocity * dt)
    step += 1
    print(step, round(np.degrees(angle_between_orientations(q, q_lighthouse)), 2))
1 139.19
2 116.69
3 94.19
4 71.69
5 49.19
6 26.69
7 4.19
8 0.0

Each step reduces the remaining angle by 22.5° (45°/s for half a second), and the last one, which had only 4.19° left, lands exactly on the target without overshooting. The whole rotation takes about 3.6 s. If the target changed halfway through the maneuver, it would be enough to pass the new quaternion: the function keeps no memory.

More than two orientations

With a sequence of orientations \(q_0, q_1, q_2, \dots\), chaining slerp from one stretch to the next produces a motion that is continuous but has abrupt changes of angular velocity at each waypoint: the axis of rotation jumps suddenly from one stretch to the next, like a road made of straight sections joined at an angle. To smooth those corners there are spherical versions of spline curves; the best known is squad (spherical quadrangle interpolation), which combines several slerps with auxiliary control orientations, in the same way that a Bézier curve combines several linear interpolations. We will not develop them here: it is enough to know that they are built from the pieces of this lesson.

Common Mistakes and Tips

  • Interpolating matrices or Euler angles directly. The former stop being rotations; the latter take detours and make jumps. Convert to quaternions, interpolate and come back.
  • Using the result of lerp without normalizing. It is not a rotation: the object shrinks halfway through the turn.
  • Forgetting the shortest path. If an object occasionally turns "the long way around", the sign change for a negative dot product is missing.
  • Applying the slerp formula with \(\Omega \approx 0\). Division by almost zero. You have to fall back on nlerp above a threshold.
  • Not clamping the cosine. Because of rounding, the dot product of two unit quaternions may be 1.0000001 and arccos returns nan. In angle_between_orientations the min prevents it; in quaternion_slerp, the threshold does.
  • Confusing \(\Omega\) with the angle of rotation. \(\Omega\) is the angle between quaternions; the actual rotation between the orientations is \(2,\Omega\).
  • Using slerp for everything. For small rotations nlerp gives a practically identical result and costs much less.
  • Unintentional "exponential" smoothing. Calling quaternion_slerp(q_current, q_target, 0.1) every frame does not produce constant speed: each time it covers 10% of what is left, so it slows down as it gets closer. It is a useful effect if that is what you want; if not, use rotate_toward.
  • Tip. To debug an interpolation, print the angle covered at several values of \(t\), as in the tables of this lesson: long-path and speed problems show up immediately.

Exercises

Exercise 1. The lighthouse lamp rotates from \(\beta = 0°\) to \(\beta = 120°\) about the vertical. a) Write the two quaternions and compute \(\Omega\). b) Compute lerp, nlerp and slerp by hand for \(t = 0.5\). c) Repeat for \(t = 0.25\) and say which angle \(\beta\) corresponds to nlerp and to slerp.

Exercise 2. A turret goes from a yaw of 170° to one of \(-170°\). a) Write the two quaternions and compute their dot product. b) What intermediate orientation (\(t = 0.5\)) is obtained without the shortest-path correction, and how many degrees does the turret sweep? c) And with the correction?

Exercise 3. Without moving from \((8, 3, 6)\), the ship must turn from its orientation \(N\) until it points at beacon Alpha, \((12, 7, 4)\), with a maximum angular velocity of 30°/s and steps of 0.5 s. a) What angle separates the two orientations? b) How many rotate_toward steps does it need? c) Check that the final nose points at the beacon.

Solutions

Solution 1.

a) \(q_0 = [1, 0, 0, 0]\) and \(q_1 = [\cos 60°, 0, \sin 60°, 0] = [0.5,\ 0,\ 0.866,\ 0]\). \(\cos\Omega = q_0 \cdot q_1 = 0.5\), so \(\Omega = 60°\) (half of 120°).

b) Lerp: \(0.5,q_0 + 0.5,q_1 = [0.75,\ 0,\ 0.433,\ 0]\), of norm \(\sqrt{0.5625 + 0.1875} = 0.866\). Nlerp: dividing by 0.866, \([0.866,\ 0,\ 0.5,\ 0]\). Slerp: both weights are \(\frac{\sin 30°}{\sin 60°} = 0.5774\), and \(0.5774,[1.5,\ 0,\ 0.866,\ 0] = [0.866,\ 0,\ 0.5,\ 0]\). Nlerp and slerp coincide at the midpoint: \([\cos 30°, 0, \sin 30°, 0]\), that is, \(\beta = 60°\).

c) Lerp: \(0.75,q_0 + 0.25,q_1 = [0.875,\ 0,\ 0.2165,\ 0]\), of norm 0.9014. Nlerp: \([0.9707,\ 0,\ 0.2402,\ 0]\); the half angle is \(\arctan(0.2165 / 0.875) = 13.90°\), so \(\beta \approx 27.80°\). Slerp: weights \(\frac{\sin 45°}{\sin 60°} = 0.8165\) and \(\frac{\sin 15°}{\sin 60°} = 0.2989\); \(q = [0.8165 + 0.1494,\ 0,\ 0.2588,\ 0] = [0.9659,\ 0,\ 0.2588,\ 0]\), which is exactly \(\beta = 30°\). Nlerp is 2.2° behind in the first quarter of the journey.

q_0 = np.array([1.0, 0.0, 0.0, 0.0])
q_120 = quaternion_from_axis_angle([0.0, 1.0, 0.0], np.radians(120.0))
for t in (0.5, 0.25):
    n, s = quaternion_nlerp(q_0, q_120, t), quaternion_slerp(q_0, q_120, t)
    print(t, np.round(n, 4), round(np.degrees(angle_between_orientations(q_0, n)), 2),
          np.round(s, 4), round(np.degrees(angle_between_orientations(q_0, s)), 2))
0.5 [0.866 0.    0.5   0.   ] 60.0 [0.866 0.    0.5   0.   ] 60.0
0.25 [0.9707 0.     0.2402 0.    ] 27.8 [0.9659 0.     0.2588 0.    ] 30.0

Solution 2.

a) \(q_0 = [\cos 85°, 0, \sin 85°, 0] = [0.0872,\ 0,\ 0.9962,\ 0]\) and \(q_1 = [\cos(-85°), 0, \sin(-85°), 0] = [0.0872,\ 0,\ -0.9962,\ 0]\). Dot product: \(0.0076 - 0.9924 = -0.9848\). Negative.

b) Without the correction, the sum \(q_0 + q_1 = [0.1743, 0, 0, 0]\) normalized is \([1, 0, 0, 0]\): a yaw of 0°. The turret passes through 0°, sweeping \(170° + 170° = 340°\). (It is the angle \(2,\Omega\) with \(\Omega = \arccos(-0.9848) = 170°\).)

c) With the correction we interpolate toward \(-q_1 = [-0.0872,\ 0,\ 0.9962,\ 0]\). The sum, \([0, 0, 1.9924, 0]\), normalized gives \([0, 0, 1, 0]\): a yaw of 180°. The turret passes through 180° and sweeps only 20°.

q_170 = quaternion_from_axis_angle([0.0, 1.0, 0.0], np.radians(170.0))
q_minus_170 = quaternion_from_axis_angle([0.0, 1.0, 0.0], np.radians(-170.0))
print(round(float(np.sum(q_170 * q_minus_170)), 4),
      np.round(quaternion_slerp(q_170, q_minus_170, 0.5), 4) + 0.0,
      round(np.degrees(angle_between_orientations(q_170, q_minus_170)), 2))
-0.9848 [0. 0. 1. 0.] 20.0

Solution 3.

beacon_alpha = np.array([12.0, 7.0, 4.0])
q_alpha = matrix_to_quaternion(orthonormal_basis(displacement(ship, beacon_alpha)))
print(round(np.degrees(angle_between_orientations(q_start, q_alpha)), 2))

q, steps = q_start.copy(), 0
while angle_between_orientations(q, q_alpha) > 1e-9:
    q = rotate_toward(q, q_alpha, np.radians(30.0) * 0.5)
    steps += 1
print(steps)
print(np.round(rotate_with_quaternion(q, [0.0, 0.0, 1.0]), 4), np.round((beacon_alpha - ship) / 6.0, 4))
74.75
5
[ 0.6667  0.6667 -0.3333] [ 0.6667  0.6667 -0.3333]

a) The orientations are 74.75° apart. (This is not the angle between the two noses, which is 70.53°: the orientation also includes where the wings end up.)

b) Each step allows \(30° \times 0.5 = 15°\). It takes four full steps (60°) and a fifth for the remaining 14.75°: 5 steps, 2.5 s.

c) The final nose is \((2/3,\ 2/3,\ -1/3)\), the unit direction from the ship to the beacon (the displacement \((4, 4, -2)\) divided by its norm, 6).

Conclusion

Interpolating orientations requires every intermediate state to be a valid rotation, the turn to follow the shortest path and, if possible, to advance at a uniform pace. Matrices interpolated entry by entry lose their orthogonality, and Euler angles take detours; unit quaternions, on the other hand, are points on a sphere, and between two points on a sphere there is a natural path: the great-circle arc. Lerp takes a shortcut along the chord and leaves the sphere; nlerp repairs it by normalizing, at minimal cost and with a speed that is not quite constant; slerp travels along it at uniform angular velocity with the formula of the sines. In all three cases the shortest path has to be chosen by changing the sign of one quaternion when the dot product is negative, and slerp must fall back on nlerp when the angle is very small. With these pieces we have interpolated a complete pose and limited the ship's turning speed. This lesson brings Module 4 to a close: we know how to describe an orientation with Euler angles, with an axis and an angle, with a matrix or with a quaternion; we know the virtues and the pitfalls of each representation; and we know how to convert between them and move smoothly from one orientation to another. We now have all the mathematics needed to place, orient and move the objects of "Stellar Lighthouse"; the most eye-catching part is still missing: seeing them. That is what Module 5, "3D Graphics", is about. It begins with the lesson "Representing 3D Objects", where we will study how the shape of the ship, the lighthouse or an asteroid is described by means of vertices, edges and faces so that a computer can draw it.

© Copyright 2026. All rights reserved