Algorithm Search⌘K

Algorithmcore

Spherical linear interpolation

Also called slerp, quaternion slerp.

Interpolates two unit quaternions along the shorter great arc between them, which turns a body about one fixed axis at constant angular speed from the first orientation to the second.

Time
Θ(1) worst
Space
Θ(1) extra
Where
n = the number of quaternion components, fixed at n = 4
Properties
deterministicnot exactofflineiterative

Spherical linear interpolation, or slerp, takes two unit quaternions q0q_0 and q1q_1 and a number t∈[0,1]t \in [0, 1], and returns the point at the fraction tt of the great arc from q0q_0 to q1q_1 on the unit sphere of R4\mathbb{R}^4:

slerp⁡(q0,q1,t)=sin⁡((1−t)Ω)sin⁡Ω q0+sin⁡(tΩ)sin⁡Ω q1=q0 (q0∗q1)t,\operatorname{slerp}(q_0, q_1, t) = \frac{\sin((1 - t)\Omega)}{\sin\Omega}\, q_0 + \frac{\sin(t\Omega)}{\sin\Omega}\, q_1 = q_0\,(q_0^* q_1)^t,

where Ω\Omega is the angle between q0q_0 and q1q_1 as vectors of R4\mathbb{R}^4. As rotations, the result turns the body from the first orientation to the second about one fixed axis at a constant angular speed. Shoemake brought the method to computer animation in 1985, and it is the standard way to interpolate orientations in graphics and robotics.

In plain words

You have two orientations of a body and you want the ones in between. A unit quaternion is a point on a sphere in four dimensions, and each orientation is such a point. Slerp walks along the shortest circle on that sphere from the first point to the second, at a steady pace. For the body, this means one steady turn about one fixed line. Each orientation has two points on the sphere, opposite to each other. If you pick the wrong one, the body turns the long way round, so slerp first picks the point that is nearer. When the two points are almost equal, a plain straight line between them, pushed back onto the sphere, is as good and avoids a division by zero.

The problem

The input is two unit quaternions q0q_0 and q1q_1, in the Hamilton convention with the scalar first, and a number tt, usually in [0,1][0, 1]. They stand for the rotations R0R_0 and R1R_1, with R(q) vR(q)\,v equal to the vector part of q (0,v) q∗q\,(0, v)\,q^*. The output is a unit quaternion q(t)q(t) such that q(0)=q0q(0) = q_0, q(1)=±q1q(1) = \pm q_1, and

R(q(t))=R0 et [w],w=log⁡(R0TR1),R(q(t)) = R_0\, e^{t\,[w]}, \qquad w = \log(R_0^{\mathsf T} R_1),

where log⁡\log is the logarithm map of SO(3) with ∣w∣≤π|w| \le \pi. So q(t)q(t) is the rotation R0R_0 followed by the fraction tt of the relative rotation R0TR1R_0^{\mathsf T} R_1, about the axis w/∣w∣w/|w| in the frame of R0R_0.

The algorithm

The algorithm takes the angle Ω\Omega from atan2, Ω=2atan2⁡(∣q1−q0∣,∣q1+q0∣)\Omega = 2\operatorname{atan2}(|q_1 - q_0|, |q_1 + q_0|), which is accurate at every angle. This is the angle of the isosceles triangle with sides q0q_0 and q1q_1: the chord ∣q1−q0∣=2sin⁡Ω2|q_1 - q_0| = 2\sin\frac\Omega2 and the sum ∣q1+q0∣=2cos⁡Ω2|q_1 + q_0| = 2\cos\frac\Omega2. The threshold is δ=10−6\delta = 10^{-6}.

  1. SLERP(q₀, q₁, t) ▷ unit quaternions; returns the point at t on the short arc
  2. 1d ← q₀ · q₁ ▷ the dot product in R⁴, d = cos Ω
  3. 2if d < 0 then
  4. 3q₁ ← -q₁ ▷ the same rotation, on the near side of the sphere
  5. 4Ω ← 2 atan2(|q₁ - q₀|, |q₁ + q₀|) ▷ the angle between q₀ and q₁, in [0, π/2]
  6. 5if Ω < δ then ▷ the two points almost agree
  7. 6q ← (1 - t) q₀ + t q₁
  8. 7return q / |q|
  9. 8a ← sin((1 - t) Ω) / sin Ω
  10. 9b ← sin(t Ω) / sin Ω
  11. 10return a q₀ + b q₁

Lines L1 to L3 choose the sign of q1q_1 that makes the arc short. Line L4 computes the angle of the arc. Lines L6 and L7 are the normalized linear interpolation, used only for tiny arcs. Lines L8 to L10 are the slerp formula.

Example

Interpolate from the identity q0=(1,0,0,0)q_0 = (1, 0, 0, 0) to the rotation by 90 degrees about zz, q1=(0.70711,0,0,0.70711)q_1 = (0.70711, 0, 0, 0.70711), at t=0.25t = 0.25.

  • Line L1: d=0.70711≥0d = 0.70711 \ge 0, so line L3 is not used.
  • Line L4: ∣q1−q0∣=0.76537|q_1 - q_0| = 0.76537 and ∣q1+q0∣=1.84776|q_1 + q_0| = 1.84776, so Ω=2atan2⁡(0.76537,1.84776)=0.78540=π/4\Omega = 2\operatorname{atan2}(0.76537, 1.84776) = 0.78540 = \pi/4.
  • Lines L8 and L9: a=sin⁡(3π/16)/sin⁡(π/4)=0.78569a = \sin(3\pi/16)/\sin(\pi/4) = 0.78569 and b=sin⁡(π/16)/sin⁡(π/4)=0.27590b = \sin(\pi/16)/\sin(\pi/4) = 0.27590.
  • Line L10: q=0.78569 (1,0,0,0)+0.27590 (0.70711,0,0,0.70711)=(0.98079,0,0,0.19509)q = 0.78569\,(1, 0, 0, 0) + 0.27590\,(0.70711, 0, 0, 0.70711) = (0.98079, 0, 0, 0.19509).

This is (cos⁡11.25°,0,0,sin⁡11.25°)(\cos 11.25°, 0, 0, \sin 11.25°), the rotation by 22.5 degrees about zz, which is one quarter of 90 degrees, as it must be. The normalized linear interpolation of lines L6 and L7 at the same tt gives (0.98229,0,0,0.18737)(0.98229, 0, 0, 0.18737), the rotation by 21.598 degrees, so it does not move at a constant speed.

The sign test matters for rotations that are near each other but have quaternions far apart. Take the rotations by 170 degrees and by −170-170 degrees about zz, with q0=(0.08716,0,0,0.99619)q_0 = (0.08716, 0, 0, 0.99619) and q1=(0.08716,0,0,−0.99619)q_1 = (0.08716, 0, 0, -0.99619). The two rotations differ by only 20 degrees, but d=cos⁡170°=−0.98481d = \cos 170° = -0.98481. Without line L3, the midpoint would be proportional to q0+q1=(0.17431,0,0,0)q_0 + q_1 = (0.17431, 0, 0, 0), which is the identity: the body would turn back through 0 degrees, the long way of 340 degrees. With line L3, q1q_1 becomes (−0.08716,0,0,0.99619)(-0.08716, 0, 0, 0.99619), Ω=10\Omega = 10 degrees, and the midpoint is (0,0,0,1)(0, 0, 0, 1), the rotation by 180 degrees, halfway along the short way.

As a check with the matrix form, the midpoint between the identity and q1=(0.5,0.5,0.5,0.5)q_1 = (0.5, 0.5, 0.5, 0.5), the rotation by 2π/32\pi/3 about (1,1,1)/3(1, 1, 1)/\sqrt3, is (0.86603,0.28868,0.28868,0.28868)(0.86603, 0.28868, 0.28868, 0.28868). Its logarithm is (0.60460,0.60460,0.60460)(0.60460, 0.60460, 0.60460), the rotation by π/3\pi/3 about the same axis.

Correctness

After lines L1 to L3, q0⋅q1≥0q_0 \cdot q_1 \ge 0, so Ω∈[0,π/2]\Omega \in [0, \pi/2], and the relative rotation q0∗q1=(cos⁡Ω,sin⁡Ω u^)q_0^* q_1 = (\cos\Omega, \sin\Omega\,\hat u) turns by the angle 2Ω≤π2\Omega \le \pi about the unit axis u^\hat u. Write q1=cos⁡Ω q0+sin⁡Ω pq_1 = \cos\Omega\, q_0 + \sin\Omega\, p, where pp is a unit vector of R4\mathbb{R}^4 orthogonal to q0q_0. Then the great arc is cos⁡(tΩ) q0+sin⁡(tΩ) p\cos(t\Omega)\, q_0 + \sin(t\Omega)\, p, and substituting pp gives the formula of lines L8 to L10. Left multiplication by q0q_0 is an isometry of R4\mathbb{R}^4 that maps 11 to q0q_0 and q0∗q1q_0^* q_1 to q1q_1, so the arc is also q0(cos⁡(tΩ)+sin⁡(tΩ) u^)=q0(q0∗q1)tq_0 (\cos(t\Omega) + \sin(t\Omega)\,\hat u) = q_0 (q_0^* q_1)^t. The factor (q0∗q1)t(q_0^* q_1)^t is the rotation by 2tΩ2t\Omega about u^\hat u, which is et[w]e^{t[w]} with w=2Ωu^=log⁡(R0TR1)w = 2\Omega\hat u = \log(R_0^{\mathsf T} R_1). For Ω<δ\Omega < \delta, the normalized linear interpolation lies on the same arc, and its angle differs from tΩt\Omega by at most about 0.016 Ω30.016\,\Omega^3, which is below 2⋅10−202 \cdot 10^{-20}. The proof gives the details.

Proof: SLERP returns the point at the fraction t of the short arcfull

We use the notation of the page. Quaternions are in the Hamilton convention, scalar first, and we treat them also as vectors of R4\mathbb{R}^4 with the usual dot product and length. For unit quaternions, ∣pq∣=∣p∣ ∣q∣|pq| = |p|\,|q|, and left or right multiplication by a unit quaternion is a linear isometry of R4\mathbb{R}^4. A unit quaternion qq gives the rotation R(q)R(q) with R(q)vR(q)v equal to the vector part of q (0,v) q∗q\,(0, v)\,q^*, and R(pq)=R(p)R(q)R(pq) = R(p)R(q), R(−q)=R(q)R(-q) = R(q).

The sign test

Lemma 1. After lines L1 to L3, q0⋅q1≥0q_0 \cdot q_1 \ge 0, and q1q_1 is a quaternion of the same rotation as the input q1q_1.

Proof. If d<0d < 0, line L3 replaces q1q_1 by −q1-q_1, and q0⋅(−q1)=−d>0q_0 \cdot (-q_1) = -d > 0. Since R(−q1)=R(q1)R(-q_1) = R(q_1), the rotation does not change. □\square

The angle

Lemma 2. Let q0q_0 and q1q_1 be unit vectors with q0⋅q1=cos⁡Ωq_0 \cdot q_1 = \cos\Omega, Ω∈[0,π]\Omega \in [0, \pi]. Then ∣q1−q0∣=2sin⁡Ω2|q_1 - q_0| = 2\sin\frac\Omega2, ∣q1+q0∣=2cos⁡Ω2|q_1 + q_0| = 2\cos\frac\Omega2, and line L4 returns Ω\Omega. After Lemma 1, Ω∈[0,π/2]\Omega \in [0, \pi/2].

Proof. ∣q1∓q0∣2=2∓2cos⁡Ω|q_1 \mp q_0|^2 = 2 \mp 2\cos\Omega, which is 4sin⁡2Ω24\sin^2\frac\Omega2 or 4cos⁡2Ω24\cos^2\frac\Omega2. Both square roots are of numbers that are not negative, and Ω2∈[0,π2]\frac\Omega2 \in [0, \frac\pi2], so atan2⁡(2sin⁡Ω2,2cos⁡Ω2)=Ω2\operatorname{atan2}(2\sin\frac\Omega2, 2\cos\frac\Omega2) = \frac\Omega2. If cos⁡Ω≥0\cos\Omega \ge 0, then Ω≤π/2\Omega \le \pi/2. □\square

The arc formula

Lemma 3. Let 0<Ω≤π/20 < \Omega \le \pi/2. The great circle arc from q0q_0 to q1q_1 with constant speed, γ:[0,1]→S3\gamma : [0, 1] \to S^3, is

γ(t)=sin⁡((1−t)Ω)sin⁡Ω q0+sin⁡(tΩ)sin⁡Ω q1,\gamma(t) = \frac{\sin((1 - t)\Omega)}{\sin\Omega}\, q_0 + \frac{\sin(t\Omega)}{\sin\Omega}\, q_1,

and the angle between γ(s)\gamma(s) and γ(t)\gamma(t) is ∣t−s∣ Ω|t - s|\,\Omega.

Proof. Put p=(q1−cos⁡Ω q0)/sin⁡Ωp = (q_1 - \cos\Omega\, q_0)/\sin\Omega. Then p⋅q0=(cos⁡Ω−cos⁡Ω)/sin⁡Ω=0p \cdot q_0 = (\cos\Omega - \cos\Omega)/\sin\Omega = 0 and ∣p∣2=(1−2cos⁡2Ω+cos⁡2Ω)/sin⁡2Ω=1|p|^2 = (1 - 2\cos^2\Omega + \cos^2\Omega)/\sin^2\Omega = 1. So q0q_0 and pp are orthonormal, and q1=cos⁡Ω q0+sin⁡Ω pq_1 = \cos\Omega\, q_0 + \sin\Omega\, p. The great circle in their plane is γ(t)=cos⁡(tΩ) q0+sin⁡(tΩ) p\gamma(t) = \cos(t\Omega)\, q_0 + \sin(t\Omega)\, p, with γ(0)=q0\gamma(0) = q_0 and γ(1)=q1\gamma(1) = q_1, and γ(s)⋅γ(t)=cos⁡((t−s)Ω)\gamma(s) \cdot \gamma(t) = \cos((t - s)\Omega). Substituting pp gives

γ(t)=(cos⁡(tΩ)−sin⁡(tΩ)cos⁡Ωsin⁡Ω)q0+sin⁡(tΩ)sin⁡Ω q1,\gamma(t) = \Big(\cos(t\Omega) - \frac{\sin(t\Omega)\cos\Omega}{\sin\Omega}\Big) q_0 + \frac{\sin(t\Omega)}{\sin\Omega}\, q_1,

and the first coefficient is sin⁡(Ω−tΩ)/sin⁡Ω\sin(\Omega - t\Omega)/\sin\Omega by the subtraction formula of the sine. □\square

So lines L8 to L10 return γ(t)\gamma(t) when Ω≥δ\Omega \ge \delta.

The power form and the rotations

Lemma 4. Let q0⋅q1=cos⁡Ω≥0q_0 \cdot q_1 = \cos\Omega \ge 0 and Ω>0\Omega > 0. Then q0∗q1=(cos⁡Ω,sin⁡Ω u^)q_0^* q_1 = (\cos\Omega, \sin\Omega\,\hat u) for a unit u^∈R3\hat u \in \mathbb{R}^3, and γ(t)=q0 (cos⁡(tΩ),sin⁡(tΩ) u^)\gamma(t) = q_0\,(\cos(t\Omega), \sin(t\Omega)\,\hat u). The rotation R(γ(t))R(\gamma(t)) is R0 et[w]R_0\, e^{t[w]} with w=2Ωu^=log⁡(R0TR1)w = 2\Omega\hat u = \log(R_0^{\mathsf T}R_1).

Proof. The scalar part of q0∗q1q_0^* q_1 is q0⋅q1=cos⁡Ωq_0 \cdot q_1 = \cos\Omega, and q0∗q1q_0^* q_1 has length 1, so its vector part has length sin⁡Ω\sin\Omega. Let LL be the left multiplication by q0q_0. LL is a linear isometry, L(1)=q0L(1) = q_0 and L(q0∗q1)=q1L(q_0^* q_1) = q_1. The isometry maps the great arc from 11 to q0∗q1q_0^* q_1, which is (cos⁡(tΩ),sin⁡(tΩ)u^)(\cos(t\Omega), \sin(t\Omega)\hat u) by Lemma 3, to the great arc from q0q_0 to q1q_1 with the same parameter, which is γ(t)\gamma(t). The unit quaternion (cos⁡(tΩ),sin⁡(tΩ)u^)(\cos(t\Omega), \sin(t\Omega)\hat u) is the rotation by 2tΩ2t\Omega about u^\hat u, which is et[w]e^{t[w]} by Rodrigues' formula. So R(γ(t))=R0et[w]R(\gamma(t)) = R_0 e^{t[w]}. At t=1t = 1, e[w]=R0TR1e^{[w]} = R_0^{\mathsf T}R_1, and ∣w∣=2Ω≤π|w| = 2\Omega \le \pi, so ww is a value of the logarithm of R0TR1R_0^{\mathsf T}R_1; it is the only value when 2Ω<π2\Omega < \pi. □\square

The same proof with tΩt\Omega for Ω\Omega shows that (q0∗q1)t(q_0^* q_1)^t, defined as (cos⁡(tΩ),sin⁡(tΩ)u^)(\cos(t\Omega), \sin(t\Omega)\hat u), is the power used in the formula q0(q0∗q1)tq_0(q_0^* q_1)^t.

The branch for small angles

Lemma 5. Let 0≤Ω<δ0 \le \Omega < \delta and t∈[0,1]t \in [0, 1]. The point of lines L6 and L7 lies on the great arc from q0q_0 to q1q_1, at an angle φ(t)\varphi(t) from q0q_0 with ∣φ(t)−tΩ∣≤3108Ω3+O(Ω5)|\varphi(t) - t\Omega| \le \frac{\sqrt3}{108}\Omega^3 + O(\Omega^5).

Proof. If Ω=0\Omega = 0, then q1=q0q_1 = q_0 and lines L6 and L7 return q0q_0, which is γ(t)\gamma(t). Otherwise, with the orthonormal q0,pq_0, p of Lemma 3, (1−t)q0+tq1=((1−t)+tcos⁡Ω) q0+tsin⁡Ω p(1 - t)q_0 + t q_1 = ((1 - t) + t\cos\Omega)\, q_0 + t\sin\Omega\, p. For t∈[0,1]t \in [0, 1] and Ω≤π/2\Omega \le \pi/2 both coefficients are not negative and not both zero, so the normalized point is cos⁡φ q0+sin⁡φ p\cos\varphi\, q_0 + \sin\varphi\, p with φ=atan2⁡(tsin⁡Ω,1−t+tcos⁡Ω)∈[0,Ω]\varphi = \operatorname{atan2}(t\sin\Omega, 1 - t + t\cos\Omega) \in [0, \Omega]. The Taylor expansion in Ω\Omega is φ=tΩ−16t(1−t)(1−2t)Ω3+O(Ω5)\varphi = t\Omega - \frac16 t(1 - t)(1 - 2t)\Omega^3 + O(\Omega^5). The cubic t(1−t)(1−2t)t(1 - t)(1 - 2t) has the largest absolute value 3/18\sqrt3/18 on [0,1][0, 1], at t=(3∓3)/6t = (3 \mp \sqrt3)/6, which gives the bound. □\square

With δ=10−6\delta = 10^{-6}, the bound is about 1.6⋅10−201.6 \cdot 10^{-20}, far below the unit roundoff.

Conclusion

Theorem. For unit quaternions q0q_0, q1q_1 and t∈[0,1]t \in [0, 1], SLERP returns the point at the fraction tt of the shorter great arc from q0q_0 to the quaternion ±q1\pm q_1 with a dot product that is not negative, exactly when Ω≥δ\Omega \ge \delta and within the bound of Lemma 5 when Ω<δ\Omega < \delta. Its rotation is R0 etlog⁡(R0TR1)R_0\, e^{t \log(R_0^{\mathsf T}R_1)}, and it moves at the constant angular speed 2Ω2\Omega about a fixed axis.

Proof. Lemma 1 fixes the sign, Lemma 2 gives the angle, and Lemmas 3 and 5 give the two branches. Lemma 4 gives the rotation form. By Lemma 3, equal steps of tt give equal arc angles, and by Lemma 4 the rotation angle of R(γ(s))TR(γ(t))R(\gamma(s))^{\mathsf T}R(\gamma(t)) is 2∣t−s∣ Ω2|t - s|\,\Omega, about the fixed axis u^\hat u in the frame of R0R_0. □\square

Complexity

One call takes Θ(1)\Theta(1) time and space in the real RAM: one dot product, two norms of 4-vectors, one atan2, three sines and about 30 additions and multiplications. To evaluate many values of tt for the same pair, compute lines L1 to L4 and sin⁡Ω\sin\Omega once; each further point then costs two sines and 8 multiplications.

Properties

  • Constant angular speed. The arc angle grows linearly in tt, so the body turns at the constant rate 2Ω2\Omega per unit of tt about a fixed axis. Since R(t)=R0et[w]R(t) = R_0 e^{t[w]} and et[w]w=we^{t[w]} w = w, both the body and the space angular velocity are constant, equal to ww and R0wR_0 w.
  • Shortest path. The curve is a geodesic of SO(3) with its usual metric, the one that measures the angle of RaTRbR_a^{\mathsf T} R_b. After the sign test, it is the shortest such path between the two rotations, of length 2Ω≤π2\Omega \le \pi.
  • Symmetry. slerp⁡(q0,q1,t)=slerp⁡(q1,q0,1−t)\operatorname{slerp}(q_0, q_1, t) = \operatorname{slerp}(q_1, q_0, 1 - t), up to the sign that line L3 chooses.
  • Independence of frames. For unit quaternions aa and bb, slerp⁡(aq0b,aq1b,t)=a slerp⁡(q0,q1,t) b\operatorname{slerp}(a q_0 b, a q_1 b, t) = a\, \operatorname{slerp}(q_0, q_1, t)\, b. So the path does not depend on the choice of the world frame or of the body frame.
  • Unit length. The output has length 1 in exact arithmetic. In floating point its length is within a few units of the roundoff of 1.
  • Only two points. Slerp of a sequence of keyframes, one segment at a time, has a jump in the angular velocity at each key. The curve is continuous, but not smooth.

Variants and improvements

  • Normalized linear interpolation (nlerp). Lines L6 and L7 alone. The path is the same arc, but the speed is not constant; the angle error at t=0.2113t = 0.2113 is about 0.016 Ω30.016\,\Omega^3. Nlerp is cheaper and is commutative when blending several rotations with weights.
  • The matrix form. R0 etlog⁡(R0TR1)R_0\, e^{t \log(R_0^{\mathsf T} R_1)} with Rodrigues' formula and the logarithm map gives the same rotations without quaternions. It costs more, and it needs care near the angle π\pi.
  • Curves through many keys. Shoemake built Bezier curves on the sphere by the de Casteljau construction of a Bezier curve, with slerp in place of the linear interpolation. Spline schemes of this kind give a smooth angular velocity at the keys.
  • Rigid motions. Screw linear interpolation does the same for a rotation and a translation together with a dual quaternion, and moves along a screw axis.
  • Time scaling. To start and stop with zero angular speed, replace tt by a time scaling s(t)s(t), such as the cubic 3t2−2t33t^2 - 2t^3. The axis stays fixed and only the speed along the arc changes.

When to use it

Use slerp to move a body or a camera between two orientations: keyframe animation, the orientation part of a straight-line motion of an end effector, and the interpolation of a measured attitude between two time stamps of a sensor. It also gives the midpoint of two rotations, which is the simplest case of rotation averaging. Convert the end orientations from matrices with Shepperd's method. To follow a measured angular velocity instead of a fixed end point, integrate the quaternion kinematic equation.

Pitfalls

  • The long way round. Without the sign test of line L2, two close rotations can have quaternions with a negative dot product, and the body then turns by up to 360 degrees minus the right angle.
  • arccos of the dot product. Ω=arccos⁡d\Omega = \arccos d loses about half of the digits when dd is close to 1, so a tiny arc gets an angle error of about 10−810^{-8}. The atan2 form of line L4 avoids this.
  • Division by sin⁡Ω\sin\Omega. At Ω=0\Omega = 0 the formula is 0/00/0. Use the linear branch below a small threshold.
  • Interpolating Euler angles. Linear interpolation of Euler angles or roll-pitch-yaw angles gives a path that changes its axis, depends on the angle convention, and can swing wildly near gimbal lock.
  • Mixed conventions. Lines L8 to L10 use only sums and dot products in R4\mathbb{R}^4, so they work in the JPL convention (scalar last, ij=−kij = -k) as well. The power form q0(q0∗q1)tq_0 (q_0^* q_1)^t and the conversion to a matrix use the quaternion product, which differs between the conventions. Do not mix the two in one computation.
  • Angles of half a turn. If the two rotations differ by exactly π\pi, the two short paths in opposite directions have the same length, and a small change of the input switches between them.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

rbm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.

Conventions (Lynch and Park, Modern Robotics, 2017):
- A matrix is a list of rows. A vector is a flat list.
- hat3(w) is the skew-symmetric matrix [w], so that [w] x = w x x.
- A twist or screw is a 6-vector (omega, v), angular part first.
  hat6(V) is the 4x4 matrix [[[omega], v], [0, 0]].
- A pose T is the 4x4 matrix [[R, p], [0, 1]].
- so3_exp and so3_log use exponential coordinates w = omega_hat * theta,
  with theta = |w| in [0, pi] for so3_log.
- se3_exp and se3_log use 6-vectors (w, v) = S * theta.
- Quaternions are Hamilton, scalar first: q = (w, x, y, z), with i j = k.
- Angles are in radians.

The helper holds no algorithm of a robotics page except the four maps
so3_exp, so3_log, se3_exp and se3_log. The pages so3-logarithm-map and
se3-exponential-map hold their own complete versions with comments.
"""

import math

# Below this angle, the coefficient functions of the exponential and the
# logarithm are evaluated by their Taylor series. The first omitted term
# of each series is of order theta^6 and is below 3e-16 for theta < 1e-2;
# it also multiplies [w] or [w]^2, which are small. Above the threshold,
# the closed forms such as (1 - cos(theta)) / theta^2 lose at most about
# 1e-16 / theta^2 to cancellation, which [w] or [w]^2 brings to 1e-14.
SERIES_THETA = 1e-2

# Above pi - NEAR_PI, so3_log takes the axis from the symmetric part of R
# (which is (R + I) / 2 at theta = pi) and not from the skew part.
NEAR_PI = 1e-2

# A pivot whose magnitude is at most PIVOT_TOL times the largest entry of
# the matrix makes solve, inv and pinv_right raise ValueError.
PIVOT_TOL = 1e-12


# ---------------------------------------------------------------- matrices


def zeros(n, m):
    """Return the n by m zero matrix."""
    return [[0.0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, s):
    """Return s * a for a vector or a matrix a and a number s."""
    if _is_matrix(a):
        return [[s * x for x in row] for row in a]
    return [s * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def mul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x, y):
    """Return the dot product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(x):
    """Return the Euclidean norm of a vector."""
    return math.sqrt(dot(x, x))


def cross(a, b):
    """Return the cross product a x b of two 3-vectors."""
    return [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]


def _max_abs(a):
    return max((abs(x) for row in a for x in row), default=0.0)


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    a is a square matrix. b is a vector or a matrix with one column per
    right-hand side; the result has the same shape as b. Raise ValueError
    if a pivot is at most PIVOT_TOL times the largest entry of a.
    """
    n = len(a)
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    m = [list(map(float, row)) + list(map(float, r)) for row, r in zip(a, rhs)]
    k = len(rhs[0]) if rhs else 0
    tol = PIVOT_TOL * _max_abs(a)
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if abs(m[piv][c]) <= tol or m[piv][c] == 0.0:
            raise ValueError("matrix is singular to working precision")
        m[c], m[piv] = m[piv], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            if f != 0.0:
                row_r, row_c = m[r], m[c]
                for j in range(c, n + k):
                    row_r[j] -= f * row_c[j]
    x = [[0.0] * k for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(k):
            s = m[r][n + j] - sum(m[r][i] * x[i][j] for i in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def inv(a):
    """Return the inverse of the square matrix a (see solve for errors)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a by elimination."""
    n = len(a)
    m = [list(map(float, row)) for row in a]
    d = 1.0
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[piv][c] == 0.0:
            return 0.0
        if piv != c:
            m[c], m[piv] = m[piv], m[c]
            d = -d
        d *= m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            for j in range(c, n):
                m[r][j] -= f * m[c][j]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T.

    a must be symmetric positive definite. Raise ValueError if a diagonal
    entry of the factor is not positive.
    """
    n = len(a)
    low = zeros(n, n)
    for i in range(n):
        for j in range(i + 1):
            s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
            if i == j:
                if s <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = math.sqrt(s)
            else:
                low[i][j] = s / low[j][j]
    return low


def pinv_right(j):
    """Return the right pseudoinverse J^T (J J^T)^(-1) of a J with full row rank."""
    jt = transpose(j)
    return mul(jt, inv(mul(j, jt)))


# ---------------------------------------------------------------- hat and vee


def hat3(w):
    """Return the 3x3 skew-symmetric matrix [w] of a 3-vector w."""
    return [
        [0.0, -w[2], w[1]],
        [w[2], 0.0, -w[0]],
        [-w[1], w[0], 0.0],
    ]


def vee3(m):
    """Return the 3-vector w of a skew-symmetric matrix m = [w]."""
    return [m[2][1], m[0][2], m[1][0]]


def hat6(v):
    """Return the 4x4 matrix [V] = [[[omega], v], [0, 0]] of V = (omega, v)."""
    w = hat3(v[:3])
    return [
        [w[0][0], w[0][1], w[0][2], v[3]],
        [w[1][0], w[1][1], w[1][2], v[4]],
        [w[2][0], w[2][1], w[2][2], v[5]],
        [0.0, 0.0, 0.0, 0.0],
    ]


def vee6(m):
    """Return the 6-vector (omega, v) of a 4x4 matrix [V]."""
    return [m[2][1], m[0][2], m[1][0], m[0][3], m[1][3], m[2][3]]


# ---------------------------------------------------------------- rotations


def rot_x(a):
    """Return the rotation by a radians about the x axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a):
    """Return the rotation by a radians about the y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a):
    """Return the rotation by a radians about the z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def rpy(roll, pitch, yaw):
    """Return R = Rz(yaw) Ry(pitch) Rx(roll)."""
    return mul(rot_z(yaw), mul(rot_y(pitch), rot_x(roll)))


def so3_exp(w):
    """Return exp([w]) for exponential coordinates w = omega_hat * theta.

    Rodrigues' formula in the form I + A [w] + B [w]^2 with
    A = sin(theta) / theta and B = (1 - cos(theta)) / theta^2.
    """
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        a = 1.0 - t2 / 6.0 + t2 * t2 / 120.0
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
    else:
        a = math.sin(t) / t
        b = (1.0 - math.cos(t)) / (t * t)
    k = hat3(w)
    k2 = mul(k, k)
    return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]


def so3_log(r):
    """Return w = omega_hat * theta with exp([w]) = r and theta in [0, pi].

    theta = atan2(|s|, c), where c = (trace(r) - 1) / 2 = cos(theta) and
    s = vee(r - r^T) / 2 = sin(theta) omega_hat. For theta below
    SERIES_THETA, w = s (1 + theta^2 / 6 + 7 theta^4 / 360). For theta
    above pi - NEAR_PI, the axis comes from the symmetric part
    ((r + r^T) / 2 - c I) / (1 - c) = omega_hat omega_hat^T, and its sign
    from s. At theta = pi both signs are valid; the sign is then chosen so
    that the largest component of the axis is positive.
    """
    c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0
    c = max(-1.0, min(1.0, c))
    s = [(r[2][1] - r[1][2]) / 2.0, (r[0][2] - r[2][0]) / 2.0, (r[1][0] - r[0][1]) / 2.0]
    sn = norm(s)
    t = math.atan2(sn, c)
    if t < SERIES_THETA:
        t2 = t * t
        f = 1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0
        return [f * x for x in s]
    if t <= math.pi - NEAR_PI:
        return [t / sn * x for x in s]
    b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
    # b = (1 - c) omega_hat omega_hat^T. Its column k with the largest
    # diagonal entry is (1 - c) omega_k omega_hat, with omega_k^2 >= 1/3.
    k = max(range(3), key=lambda i: b[i][i])
    col = [b[i][k] for i in range(3)]
    axis = [x / norm(col) for x in col]
    if dot(axis, s) < 0.0 or (dot(axis, s) == 0.0 and axis[k] < 0.0):
        axis = [-x for x in axis]
    return [t * x for x in axis]


# ---------------------------------------------------------------- poses


def make_T(r, p):
    """Return the 4x4 pose [[r, p], [0, 1]]."""
    return [
        [r[0][0], r[0][1], r[0][2], p[0]],
        [r[1][0], r[1][1], r[1][2], p[1]],
        [r[2][0], r[2][1], r[2][2], p[2]],
        [0.0, 0.0, 0.0, 1.0],
    ]


def _rp(t):
    return [row[:3] for row in t[:3]], [t[0][3], t[1][3], t[2][3]]


def T_inv(t):
    """Return the inverse [[R^T, -R^T p], [0, 1]] of a pose t."""
    r, p = _rp(t)
    rt = transpose(r)
    return make_T(rt, [-x for x in matvec(rt, p)])


def T_apply(t, x):
    """Return R x + p, the image of the point x under the pose t."""
    r, p = _rp(t)
    return add(matvec(r, x), p)


def se3_exp(xi):
    """Return exp([xi]) for a 6-vector xi = (w, v) = S * theta.

    The rotation is so3_exp(w). The translation is G v with
    G = I + B [w] + C [w]^2, B = (1 - cos(theta)) / theta^2 and
    C = (theta - sin(theta)) / theta^3, theta = |w|. For w = 0 this is a
    translation by v.
    """
    w, v = xi[:3], xi[3:]
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
        c = 1.0 / 6.0 - t2 / 120.0 + t2 * t2 / 5040.0
    else:
        b = (1.0 - math.cos(t)) / (t * t)
        c = (t - math.sin(t)) / (t * t * t)
    k = hat3(w)
    k2 = mul(k, k)
    g = [[(1.0 if i == j else 0.0) + b * k[i][j] + c * k2[i][j] for j in range(3)] for i in range(3)]
    return make_T(so3_exp(w), matvec(g, v))


def se3_log(t):
    """Return the 6-vector xi = (w, v) with se3_exp(xi) = t and |w| in [0, pi].

    w = so3_log(R) and v = G^(-1) p with
    G^(-1) = I - [w] / 2 + D [w]^2, D = (1 - (theta / 2) cot(theta / 2)) / theta^2.
    """
    r, p = _rp(t)
    w = so3_log(r)
    th = norm(w)
    if th < SERIES_THETA:
        t2 = th * th
        d = 1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0
    else:
        half = th / 2.0
        d = (1.0 - half * math.cos(half) / math.sin(half)) / (th * th)
    k = hat3(w)
    k2 = mul(k, k)
    gi = [[(1.0 if i == j else 0.0) - 0.5 * k[i][j] + d * k2[i][j] for j in range(3)] for i in range(3)]
    return w + matvec(gi, p)


def adjoint(t):
    """Return the 6x6 adjoint [[R, 0], [[p] R, R]] of a pose t."""
    r, p = _rp(t)
    pr = mul(hat3(p), r)
    out = zeros(6, 6)
    for i in range(3):
        for j in range(3):
            out[i][j] = r[i][j]
            out[i + 3][j + 3] = r[i][j]
            out[i + 3][j] = pr[i][j]
    return out


# ---------------------------------------------------------------- quaternions


def quat_mul(q, r):
    """Return the Hamilton product q r of quaternions (w, x, y, z)."""
    a1, b1, c1, d1 = q
    a2, b2, c2, d2 = r
    return [
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    ]


def quat_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return [q[0], -q[1], -q[2], -q[3]]


def quat_to_rot(q):
    """Return the rotation matrix of the quaternion q, so that (0, R v) = q (0, v) q*.

    q need not be of unit length; the result is the rotation of q / |q|.
    """
    w, x, y, z = q
    n = w * w + x * x + y * y + z * z
    s = 2.0 / n
    return [
        [1.0 - s * (y * y + z * z), s * (x * y - w * z), s * (x * z + w * y)],
        [s * (x * y + w * z), 1.0 - s * (x * x + z * z), s * (y * z - w * x)],
        [s * (x * z - w * y), s * (y * z + w * x), 1.0 - s * (x * x + y * y)],
    ]


def quat_from_axis_angle(axis, angle):
    """Return (cos(angle / 2), sin(angle / 2) axis / |axis|).

    A zero axis is allowed only with angle 0 (the identity); otherwise
    raise ValueError.
    """
    n = norm(axis)
    if n == 0.0:
        if angle == 0.0:
            return [1.0, 0.0, 0.0, 0.0]
        raise ValueError("zero axis with a nonzero angle")
    s = math.sin(angle / 2.0) / n
    return [math.cos(angle / 2.0), s * axis[0], s * axis[1], s * axis[2]]


# ---------------------------------------------------------------- derivatives


def num_jacobian(f, x, h=1e-6):
    """Return the Jacobian of f at x by central differences with step h.

    f maps a list of n numbers to a list of m numbers; the result is m by n.
    """
    cols = []
    for i in range(len(x)):
        xp = list(x)
        xm = list(x)
        xp[i] += h
        xm[i] -= h
        fp, fm = f(xp), f(xm)
        cols.append([(a - b) / (2.0 * h) for a, b in zip(fp, fm)])
    return transpose(cols)


# ---------------------------------------------------------------- self-test


def self_test():
    """Check the area check values; return True or raise AssertionError."""
    r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
    want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
    assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
    w = so3_log(want)
    assert abs(norm(w) - 2.0943951) < 1e-7
    assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
    t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
    want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
    assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
    return True
spherical_linear_interpolation.py 84 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spherical-linear-interpolation/. The authors are listed in prov/BJ0DKQ.jsonl.
"""Spherical linear interpolation (slerp) of unit quaternions.

Quaternions use the Hamilton convention, scalar first, q = (w, x, y, z).
slerp(q0, q1, t) returns the point at the fraction t of the great arc from
q0 to q1 on the unit sphere of R^4:

    slerp(q0, q1, t) = sin((1 - t) W) / sin(W) q0 + sin(t W) / sin(W) q1,

where W is the angle between q0 and q1 in R^4. This equals q0 (q0* q1)^t.
If q0 . q1 < 0, q1 is replaced by -q1 first. Both give the same rotation,
and the replacement makes the arc the short one, so the rotation turns by
at most pi. W comes from atan2 of |q1 - q0| and |q1 + q0|, which is
accurate at every angle. For W below SMALL_ANGLE, the normalized linear
interpolation is used. Its point lies on the same arc, at an angle that
differs from t W by -t (1 - t) (1 - 2 t) W^3 / 6 to leading order, which is
at most about 0.016 W^3.

slerp_power(q0, q1, t) is the second method: q0 (q0* q1)^t with the power
taken through the axis and the angle. It is here for the tests.
"""

import math

# Below this angle (in radians, on the sphere of R^4), slerp is replaced by
# the normalized linear interpolation. Its error there is below 2e-20.
SMALL_ANGLE = 1e-6


def _norm(q):
    return math.sqrt(sum(a * a for a in q))


def slerp(q0, q1, t):
    """Return the unit quaternion at the fraction t of the short arc from q0 to q1."""
    d = sum(a * b for a, b in zip(q0, q1))  # @line L1
    if d < 0.0:  # @line L2
        q1 = [-a for a in q1]  # @line L3
    a = _norm([y - x for x, y in zip(q0, q1)])
    b = _norm([y + x for x, y in zip(q0, q1)])
    big_w = 2.0 * math.atan2(a, b)  # @line L4
    if big_w < SMALL_ANGLE:  # @line L5
        q = [(1.0 - t) * x + t * y for x, y in zip(q0, q1)]  # @line L6
        n = _norm(q)
        return [x / n for x in q]  # @line L7
    s = math.sin(big_w)
    c0 = math.sin((1.0 - t) * big_w) / s  # @line L8
    c1 = math.sin(t * big_w) / s  # @line L9
    return [c0 * x + c1 * y for x, y in zip(q0, q1)]  # @line L10


def _mul(q, r):
    a1, b1, c1, d1 = q
    a2, b2, c2, d2 = r
    return [
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    ]


def quat_pow(q, t):
    """Return q^t for a unit quaternion q = (cos h, sin h u) with q[0] >= 0.

    q^t = (cos(t h), sin(t h) u), with h = atan2(|v|, w) in [0, pi / 2].
    For q = (1, 0, 0, 0) the result is (1, 0, 0, 0).
    """
    v = q[1:]
    s = _norm(v)
    if s == 0.0:
        return [1.0, 0.0, 0.0, 0.0]
    h = math.atan2(s, q[0])
    f = math.sin(t * h) / s
    return [math.cos(t * h)] + [f * x for x in v]


def slerp_power(q0, q1, t):
    """Return q0 (q0* q1)^t, after the sign flip of q1 for the short arc."""
    if sum(a * b for a, b in zip(q0, q1)) < 0.0:
        q1 = [-a for a in q1]
    rel = _mul([q0[0], -q0[1], -q0[2], -q0[3]], q1)
    return _mul(q0, quat_pow(rel, t))
test_spherical_linear_interpolation.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spherical-linear-interpolation/. The authors are listed in prov/BJ0DKQ.jsonl.
"""Tests of spherical linear interpolation.

The references are the power form q0 (q0* q1)^t, and the matrix form
R0 exp(t log(R0^T R1)) built from the shared helper rbm (so3_exp, so3_log
and quat_to_rot), which does not use quaternions for the interpolation.
"""

import math
import random

import rbm
from spherical_linear_interpolation import SMALL_ANGLE, slerp, slerp_power


def unit(rng, n=4):
    while True:
        v = [rng.gauss(0.0, 1.0) for _ in range(n)]
        s = math.sqrt(sum(x * x for x in v))
        if s > 1e-3:
            return [x / s for x in v]


def mdiff(a, b):
    return max(abs(a[i][j] - b[i][j]) for i in range(3) for j in range(3))


def qdiff(p, q):
    return max(abs(a - b) for a, b in zip(p, q))


def angle_between(p, q):
    """The rotation angle of p* q, in [0, pi], up to the sign of q."""
    a = math.sqrt(sum((x - y) ** 2 for x, y in zip(p, q)))
    b = math.sqrt(sum((x + y) ** 2 for x, y in zip(p, q)))
    return 4.0 * math.atan2(min(a, b), max(a, b))


def test_quarter_turn_about_z():
    q0 = [1.0, 0.0, 0.0, 0.0]
    q1 = rbm.quat_from_axis_angle([0.0, 0.0, 1.0], math.pi / 2.0)
    assert qdiff(q1, [0.70711, 0.0, 0.0, 0.70711]) < 1e-5
    for t in (0.0, 0.25, 0.5, 0.75, 1.0):
        want = rbm.quat_from_axis_angle([0.0, 0.0, 1.0], t * math.pi / 2.0)
        assert qdiff(slerp(q0, q1, t), want) < 1e-15
    q = slerp(q0, q1, 0.25)
    assert abs(q[0] - 0.98079) < 1e-5 and abs(q[3] - 0.19509) < 1e-5


def test_end_points():
    rng = random.Random(1)
    for _ in range(200):
        q0, q1 = unit(rng), unit(rng)
        assert qdiff(slerp(q0, q1, 0.0), q0) < 1e-15
        sign = 1.0 if sum(a * b for a, b in zip(q0, q1)) >= 0.0 else -1.0
        assert qdiff(slerp(q0, q1, 1.0), [sign * x for x in q1]) < 1e-15


def test_against_power_form_and_matrix_form():
    rng = random.Random(2)
    for _ in range(200):
        q0, q1 = unit(rng), unit(rng)
        r0, r1 = rbm.quat_to_rot(q0), rbm.quat_to_rot(q1)
        w = rbm.so3_log(rbm.mul(rbm.transpose(r0), r1))
        if math.sqrt(sum(x * x for x in w)) > math.pi - 1e-3:
            continue
        for t in (0.1, 0.3, 0.5, 0.9):
            q = slerp(q0, q1, t)
            assert abs(sum(a * a for a in q) - 1.0) < 1e-14
            assert qdiff(q, slerp_power(q0, q1, t)) < 1e-13
            want = rbm.mul(r0, rbm.so3_exp([t * x for x in w]))
            assert mdiff(rbm.quat_to_rot(q), want) < 1e-12


def test_constant_angular_speed():
    rng = random.Random(3)
    for _ in range(50):
        q0, q1 = unit(rng), unit(rng)
        total = angle_between(q0, q1)
        steps = 10
        pts = [slerp(q0, q1, k / steps) for k in range(steps + 1)]
        for a, b in zip(pts, pts[1:]):
            assert abs(angle_between(a, b) - total / steps) < 1e-12


def test_one_fixed_axis():
    # Every intermediate rotation differs from q0 by a turn about one axis.
    rng = random.Random(4)
    for _ in range(50):
        q0, q1 = unit(rng), unit(rng)
        r0 = rbm.quat_to_rot(q0)
        axes = []
        for t in (0.2, 0.5, 0.8):
            r = rbm.quat_to_rot(slerp(q0, q1, t))
            w = rbm.so3_log(rbm.mul(rbm.transpose(r0), r))
            n = math.sqrt(sum(x * x for x in w))
            axes.append([x / n for x in w])
        for a in axes[1:]:
            assert qdiff(a, axes[0]) < 1e-10


def test_sign_flip_takes_the_short_arc():
    qa = rbm.quat_from_axis_angle([0.0, 0.0, 1.0], math.radians(170.0))
    qb = rbm.quat_from_axis_angle([0.0, 0.0, 1.0], math.radians(-170.0))
    assert sum(a * b for a, b in zip(qa, qb)) < 0.0
    mid = slerp(qa, qb, 0.5)
    # The short way from 170 to 190 degrees passes 180 degrees.
    assert qdiff(mid, [0.0, 0.0, 0.0, 1.0]) < 1e-15
    # The same rotations with the sign of qb changed give the same path.
    assert qdiff(slerp(qa, [-x for x in qb], 0.5), mid) < 1e-15


def test_small_angles():
    rng = random.Random(5)
    for scale in (1e-3, 1e-6, 0.5e-6, 1e-9, 1e-12, 0.0):
        for _ in range(50):
            q0 = unit(rng)
            u = unit(rng, 3)
            q1 = rbm.quat_mul(q0, rbm.quat_from_axis_angle(u, scale))
            for t in (0.0, 0.3, 1.0):
                want = rbm.quat_mul(q0, rbm.quat_from_axis_angle(u, t * scale)) if scale > 0.0 else q0
                q = slerp(q0, q1, t)
                assert qdiff(q, want) < 1e-15
                assert abs(sum(a * a for a in q) - 1.0) < 1e-15
    assert SMALL_ANGLE == 1e-6


def test_check_value_through_matrices():
    # Halfway from I to the rotation by 2 pi / 3 about (1, 1, 1) / sqrt(3).
    q = slerp([1.0, 0.0, 0.0, 0.0], [0.5, 0.5, 0.5, 0.5], 0.5)
    w = rbm.so3_log(rbm.quat_to_rot(q))
    assert max(abs(x - math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-14
    assert abs(q[0] - math.sqrt(3.0) / 2.0) < 1e-15

History

Shoemake (1985) introduced slerp to computer animation in his SIGGRAPH paper on quaternion curves. He compared it with the interpolation of Euler angles, and built smooth curves through many keyframes with slerp in a Bezier construction. The formula for a point on a great arc is older and comes from spherical geometry. Sola (2017) gives the equivalent forms q0(q0∗q1)tq_0 (q_0^* q_1)^t and the form on the arc in R4\mathbb{R}^4 in the Hamilton convention.

References

  1. Ken Shoemake, Animating rotation with quaternion curves, Computer Graphics (Proceedings of SIGGRAPH 1985) 19(3), 245-254, 1985, the whole paper (the slerp formula, the comparison with Euler angle interpolation, and quaternion Bezier curves built from slerp)
  2. Joan Sola, Quaternion kinematics for the error-state Kalman filter, 2017, Section 2.7 (spherical linear interpolation, equation 127: q(t) = q0 (q0* q1)^t, and the form on the 4D arc)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • at least three sources
  • a scene preset for the example