Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rotations, Euler angles and quaternions

ProblemRepresent, compose, convert and interpolate rotations of three-dimensional space
Devised byLeonhard Euler (1775), angles and the rotation theorem; Olinde Rodrigues (1840), axis–angle formula; William Rowan Hamilton (1843), quaternions; Ken Shoemake (1985), spherical interpolation
AccuracyMatrices and Euler angles agree with SciPy’s Rotation to , and slerp to (see the chapter overview)
CostComposing: 27 multiplications for matrices, 16 for quaternions; conversions
Read firstGeometric types: points, vectors, shapes and shared tables
APIRotation3 (from_axis_angle, from_euler, from_matrix, from_two_vectors, matrix, axis_angle, to_euler, rotate, inverse, slerp, angle_to), Rotation2, EulerSequence, Axis, Quaternion, nearest_rotation_matrix, rotation_matrix_axis_angle

Overview

Spacecraft attitude, robot arms, camera orientation and molecular conformations all need rotations: changes of direction that keep lengths and handedness. There are several ways to write one down, each with uses and pitfalls.

  • A rotation matrix is a orthogonal matrix of determinant 1. It acts on vectors directly, but has nine numbers for three degrees of freedom and drifts away from orthogonality under repeated products.
  • Euler angles are three successive turns about coordinate axes. They are compact and intuitive (roll, pitch and yaw), but have singular gimbal lock orientations.
  • An axis and angle describe a single turn about a fixed axis, which by Euler’s rotation theorem every rotation is.
  • A unit quaternion packs the axis–angle into four numbers. Quaternions compose by multiplication, renormalise trivially, have no singularities, and interpolate smoothly.

The library’s Rotation3 stores a unit quaternion and converts to and from the others.

Where it is used

Orientation in three dimensions is easy to get wrong, and this entry is about getting it right.

  • Aerospace and drones. Flight controllers, satellite attitude systems and inertial navigation represent orientation with quaternions to avoid the gimbal lock of Euler angles.
  • Robotics. Joint angles compose into the rotation of a gripper; interpolating between two orientations smoothly (slerp) moves a camera or arm.
  • Computer graphics and VR. Head tracking and character animation use quaternions.
  • Phones. The orientation from the gyroscope and accelerometer that rotates your screen is a quaternion.

History

Leonhard Euler showed in 1775 that every rotation of a rigid body about a fixed point is a single turn about some axis, and used three angles to describe orientation. Olinde Rodrigues (1840) gave the composition of rotations in terms of their axes and half-angles, in effect the quaternion product before quaternions. William Rowan Hamilton discovered the quaternions on 16 October 1843, walking along the Royal Canal in Dublin, and carved into Brougham Bridge. Vector algebra displaced them in physics, but they returned in spacecraft attitude control in the 1960s, where gimbal lock had real consequences: Apollo’s guidance platform had to avoid it. Ken Shoemake (1985) introduced quaternion interpolation (slerp) to computer animation.

The idea

Rotation matrices and Euler angles

A rotation of three-dimensional space is described by a matrix that is orthogonal (, so lengths and angles are preserved) and has determinant (so it is not a reflection). Its columns are the images of the three coordinate axes. Nine numbers with six constraints leave three degrees of freedom, and the different representations of a rotation are different ways of choosing three numbers (or four, with one constraint).

The simplest rotations are those about the coordinate axes. About ,

with and alike. By Euler’s theorem, every rotation is a turn by some angle about some axis. Rodrigues’ formula gives the matrix of a turn by about a unit axis : , where is the cross-product matrix.

Euler angles describe a rotation as three successive turns about coordinate axes, which is how an aircraft’s attitude or a robot’s wrist is usually specified. An Euler sequence names three axes, consecutive ones different: twelve sequences in all. The six with all three different (XYZ, ZYX, …) are Tait–Bryan angles, such as roll–pitch–yaw. The six repeating the first axis (ZXZ, …) are proper Euler angles, used for orbits and spinning tops. The library’s sequences are intrinsic: each turn is about an axis of the already-turned body, so XYZ with angles is . Recovering the angles from a matrix reads from one entry, and and from pairs of others with atan2. Each rotation has two angle triples, related by for Tait–Bryan sequences. The library returns the one with (or for proper sequences), as SciPy does.

Euler angles have an unavoidable defect. At gimbal lock ( for Tait–Bryan, or for proper), the first and third axes line up and only is determined. The library then sets . The same convention applies to Quaternion::to_euler (Z–Y–X roll, pitch and yaw).

Quaternions

Quaternions avoid gimbal lock, and are the representation of choice for composing and interpolating rotations. A quaternion is a four-component number, with three imaginary units that multiply by the rules (so that, for example, but : the multiplication is not commutative, just as rotations are not).

The connection with rotations is direct. A turn by the angle about the unit axis corresponds to the quaternion

which has unit length. It stores the axis and the (half) angle almost explicitly. A unit quaternion rotates a vector by , treating as . Composition is multiplication: applies first. Because of the half angle, and give the same rotation (turning by changes the sign of but not the rotation). This double cover matters for interpolation. A matrix becomes a quaternion by Shepperd’s method, which takes the square root of whichever of and is largest, so it never divides by a small number.

Rounding accumulates when many rotations are composed. A matrix product slowly stops being orthogonal, and a quaternion product slowly stops having unit norm:

Figure 24.1. Drift.

Both drift by about after a million steps, but repairing them differs in cost. A quaternion is renormalised by dividing by its norm, which Rotation3 does on every product. A matrix needs nearest_rotation_matrix, which computes the orthogonal polar factor by Newton’s iteration .

Spherical linear interpolation

Unit quaternions lie on a sphere in four dimensions, and rotations interpolate along its great circles. With ,

which turns at a constant angular rate about a fixed axis. If , is negated first so the shorter of the two arcs is taken. Normalised linear interpolation (nlerp) blends and renormalises. It is cheaper and follows the same path, but not at a uniform rate:

Figure 24.2. Slerp and nlerp.

Algorithm

Euler angles to a matrix: form the three elementary rotation matrices for the angles and the axes of the sequence, and multiply them in the order of the sequence.

A matrix to Euler angles.

  1. Read the middle angle from the one entry of the matrix that depends on it alone (through its sine, for a Tait-Bryan sequence, or its cosine, for a proper one).
  2. Read and , each from a pair of entries, with atan2, which returns the angle in the correct quadrant.
  3. If lies outside the documented range, replace the triple by the equivalent one inside it.
  4. At gimbal lock, where the entries used in step 2 vanish, set and compute from other entries, so that it carries the whole of the combined angle.

A matrix to a quaternion (Shepperd’s method).

  1. Compute the four candidates and for , which are four times the squares of the quaternion’s components.
  2. Take the largest and compute that component as half its square root.
  3. Compute the other three components from sums and differences of off-diagonal entries of , divided by four times the component just found.
  4. Change the sign of all four if necessary so that .

Spherical linear interpolation between and at parameter .

  1. Compute the dot product . If , negate and , so as to take the shorter arc.
  2. If is very close to 1, the quaternions are nearly equal and nearly zero: interpolate linearly and normalise.
  3. Otherwise compute and apply the formula.

Implementation

    pub fn slerp(&self, other: &Self, t: f64) -> Self {
        let mut b = *other;
        let mut d = self.dot(&b);
        if d < 0.0 {
            b = -b;
            d = -d;
        }
        if d > 1.0 - 1e-10 {
            return self.nlerp(&b, t);
        }
        let theta = d.acos();
        let s = theta.sin();
        (*self * (((1.0 - t) * theta).sin() / s) + b * ((t * theta).sin() / s)).normalized()
    }
  • Matrices are row-major [[f64; 3]; 3] acting on column vectors.
  • Rotation3 multiplication a * b applies b first; angle_to gives the angle of the rotation between two orientations.
  • Rotation2 covers the plane, with rotation about a pivot.

In practice

//! Rotation matrices, Euler angles, quaternions and interpolation.

use lib_jsl_geometry::algorithms::rotations::{is_rotation_matrix, mat3_apply};
use lib_jsl_geometry::algorithms::{EulerSequence, Quaternion, Rotation3};
use std::f64::consts::FRAC_PI_2;

fn main() {
    // A quarter turn about z, then one about the new x (intrinsic Z-X-Z with a zero last angle).
    let r = Rotation3::from_euler(EulerSequence::ZXZ, [FRAC_PI_2, FRAC_PI_2, 0.0]);
    let m = r.matrix();
    println!("matrix rows {:.3?}", m.map(|row| row.map(|v| v + 0.0)));
    println!("is a rotation: {}, x axis goes to {:.3?}", is_rotation_matrix(&m, 1e-12), mat3_apply(&m, [1.0, 0.0, 0.0]).map(|v| v + 0.0));
    let (axis, angle) = r.axis_angle();
    println!("axis {:.4?}, angle {:.4} rad", axis, angle);
    println!("as intrinsic X-Y-Z angles: {:.4?}", r.to_euler(EulerSequence::XYZ).unwrap());

    // Quaternions compose by the Hamilton product: a then b is b * a.
    let a = Quaternion::from_axis_angle([0.0, 0.0, 1.0], FRAC_PI_2);
    let b = Quaternion::from_axis_angle([1.0, 0.0, 0.0], FRAC_PI_2);
    let ab = b * a;
    println!("quaternion of a then b: {:.4} {:+.4}i {:+.4}j {:+.4}k", ab.w, ab.x, ab.y, ab.z);
    println!("rotates (1, 0, 0) to {:.3?}", ab.rotate_vector([1.0, 0.0, 0.0]).map(|v| v + 0.0));

    // Halfway along the 120 degree rotation r is a 60 degree turn.
    let half = Rotation3::identity().slerp(&r, 0.5);
    println!("slerp halfway: {:.4} rad from the start, {:.4} from the end", Rotation3::identity().angle_to(&half), half.angle_to(&r));
    println!("roll, pitch, yaw of a: {:.4?}", a.to_euler());
}
matrix rows [[0.000, 0.000, 1.000], [1.000, 0.000, 0.000], [0.000, 1.000, 0.000]]
is a rotation: true, x axis goes to [0.000, 1.000, 0.000]
axis [0.5774, 0.5774, 0.5774], angle 2.0944 rad
as intrinsic X-Y-Z angles: [1.5708, 1.5708, 0.0000]
quaternion of a then b: 0.5000 +0.5000i -0.5000j +0.5000k
rotates (1, 0, 0) to [0.000, 0.000, 1.000]
slerp halfway: 1.0472 rad from the start, 1.0472 from the end
roll, pitch, yaw of a: (0.0000, 0.0000, 1.5708)

The two quarter turns combine into a third of a turn () about the diagonal , which cycles the axes: .

Strengths

  • All twelve Euler sequences, in SciPy’s ranges, with gimbal lock handled.
  • Quaternion-based rotations that stay normalised, with slerp, nlerp, exponential and logarithm.

Weaknesses

  • Extrinsic sequences must be expressed as intrinsic ones (an extrinsic XYZ is an intrinsic ZYX with the angles reversed).
  • No rotation averaging, spline (squad) interpolation or random sampling of rotations.

Exercises

  1. Show that with is a rotation by about .
  2. Derive the formulas for intrinsic XYZ angles from the matrix entries, and the second solution .
  3. Show that at the XYZ matrix depends only on .
  4. Show that an extrinsic rotation sequence equals the intrinsic one with the axes in reverse order.
  5. Show that slerp has constant angular velocity, and that nlerp is fastest in the middle.
Hints and answers
  1. For the product decomposes into a component along (unchanged) and a perpendicular part rotated by about (use the identity ).
  2. For the matrix entry gives and the ratios of entries in the first column and last row give and via . The second solution is .
  3. At the middle rotation maps and axes so that up to sign convention: only the sum or difference matters.
  4. An extrinsic sequence about fixed axes with angles is the product , which is the intrinsic sequence with the angles in reversed order.
  5. Slerp travels along a great circle at constant speed. Nlerp interpolates linearly and renormalises: the angular speed is largest in the middle of the arc and smallest at the ends.

Further reading

  • K. Shoemake, “Animating rotation with quaternion curves”, SIGGRAPH Computer Graphics 19 (1985) 245–254.
  • J. Diebel, “Representing attitude: Euler angles, unit quaternions, and rotation vectors”, Stanford University technical report, 2006.
  • S. W. Shepperd, “Quaternion from rotation matrix”, Journal of Guidance and Control 1 (1978) 223–224.
  • S. L. Altmann, Rotations, Quaternions, and Double Groups, Oxford University Press, 1986.