TExcelTAD
Home › Math for Games › Quaternions

Quaternions

A quaternion is four numbers, (w, x, y, z), that store a 3D rotation. You don't need to visualize 4D space to use them. Think of a unit quaternion as axis-angle in a convenient package:

text
q = ( cos(θ/2),  â.x * sin(θ/2),  â.y * sin(θ/2),  â.z * sin(θ/2) )
     \_ w _/     \___________________ (x, y, z) __________________/

The half angle looks odd, but it is what makes the rest work. Every engine stores rotations this way: Unity's Quaternion, Unreal's FQuat, Godot's Quaternion, Three.js's Quaternion, glm::quat.

Why quaternions?

Euler angles 3×3 matrix Quaternion
Numbers 3 9 4
Gimbal lock yes no no
Combine two rotations awkward 27 multiplies 16 multiplies
Smooth interpolation poor poor slerp
Fix drift n/a re-orthonormalize (costly) normalize (cheap)
Human-readable yes somewhat no

A Quat struct

The key operations are building one from axis-angle, multiplying two (combining rotations), and rotating a vector. Multiplication has the same order rule as matrices: q2 * q1 applies q1 first, then q2.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>
#include <numbers>

struct Vec3 { double x, y, z; };
Vec3 operator+(Vec3 a, Vec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
Vec3 operator*(Vec3 v, double s) { return {v.x * s, v.y * s, v.z * s}; }
Vec3 cross(Vec3 a, Vec3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }

struct Quat {
    double w = 1, x = 0, y = 0, z = 0;          // identity by default

    static Quat axisAngle(Vec3 axis, double angle) {   // axis must be unit length
        double h = angle / 2, s = std::sin(h);
        return {std::cos(h), axis.x * s, axis.y * s, axis.z * s};
    }
};

Quat operator*(Quat a, Quat b) {                 // Hamilton product: apply b, then a
    return {a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,
            a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
            a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
            a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w};
}

Vec3 rotate(Quat q, Vec3 v) {                    // optimized form of q * v * conjugate(q)
    Vec3 u{q.x, q.y, q.z};
    Vec3 t = cross(u, v) * 2;
    return v + t * q.w + cross(u, t);
}

double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }
std::ostream& operator<<(std::ostream& os, Vec3 v) { return os << "(" << z0(v.x) << ", " << z0(v.y) << ", " << z0(v.z) << ")"; }
std::ostream& operator<<(std::ostream& os, Quat q) {
    return os << "[w=" << z0(q.w) << " x=" << z0(q.x) << " y=" << z0(q.y) << " z=" << z0(q.z) << "]";
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    const double k = std::numbers::pi / 180;
    Quat yaw90 = Quat::axisAngle({0, 1, 0}, 90 * k);
    Quat pitch90 = Quat::axisAngle({1, 0, 0}, 90 * k);
    std::cout << "yaw90   = " << yaw90 << "\n";
    std::cout << "rotate X by yaw90:  " << rotate(yaw90, {1, 0, 0}) << "\n";

    Vec3 forward{0, 0, -1};
    std::cout << "pitch, then yaw: " << rotate(yaw90 * pitch90, forward) << "\n";
    std::cout << "yaw, then pitch: " << rotate(pitch90 * yaw90, forward) << "\n";

    Quat twice = yaw90 * yaw90;                   // 180 degrees around Y
    std::cout << "yaw90 * yaw90 = " << twice << " -> X becomes " << rotate(twice, {1, 0, 0}) << "\n";
}
yaw90   = [w=0.707 x=0.000 y=0.707 z=0.000]
rotate X by yaw90:  (0.000, 0.000, -1.000)
pitch, then yaw: (0.000, 1.000, 0.000)
yaw, then pitch: (-1.000, 0.000, 0.000)
yaw90 * yaw90 = [w=0.000 x=0.000 y=1.000 z=0.000] -> X becomes (-1.000, 0.000, 0.000)

The two orders give the same results as the matrix version in the Euler lesson, which is the point: a quaternion is just a different storage format for the same rotation.

Conjugate, inverse and the double cover

The conjugate (w, -x, -y, -z) is the inverse rotation (for unit quaternions): same axis, opposite angle. And because of the half angle, q and -q represent the same rotation (θ/2 and θ/2 + 180° give opposite signs everywhere). This "double cover" matters for interpolation and for comparing quaternions: two rotations are equal when |dot(q1, q2)| is about 1.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>
#include <numbers>

struct Vec3 { double x, y, z; };
Vec3 operator+(Vec3 a, Vec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
Vec3 operator*(Vec3 v, double s) { return {v.x * s, v.y * s, v.z * s}; }
Vec3 cross(Vec3 a, Vec3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
struct Quat { double w, x, y, z; };
Quat conjugate(Quat q) { return {q.w, -q.x, -q.y, -q.z}; }
Quat negate(Quat q) { return {-q.w, -q.x, -q.y, -q.z}; }
double dot(Quat a, Quat b) { return a.w * b.w + a.x * b.x + a.y * b.y + a.z * b.z; }
Vec3 rotate(Quat q, Vec3 v) { Vec3 u{q.x, q.y, q.z}; Vec3 t = cross(u, v) * 2; return v + t * q.w + cross(u, t); }
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }
std::ostream& operator<<(std::ostream& os, Vec3 v) { return os << "(" << z0(v.x) << ", " << z0(v.y) << ", " << z0(v.z) << ")"; }

int main() {
    std::cout << std::fixed << std::setprecision(3);
    double h = 60 * std::numbers::pi / 180 / 2;
    Quat q{std::cos(h), 0, 0, std::sin(h)};             // 60 degrees around Z
    Vec3 p{1, 0, 0};
    Vec3 r = rotate(q, p);
    std::cout << "q rotates X to          " << r << "\n";
    std::cout << "conjugate brings it back " << rotate(conjugate(q), r) << "\n";
    std::cout << "-q rotates X to         " << rotate(negate(q), p) << "  (same rotation)\n";
    std::cout << "dot(q, -q) = " << dot(q, negate(q)) << "\n";
}
q rotates X to          (0.500, 0.866, 0.000)
conjugate brings it back (1.000, 0.000, 0.000)
-q rotates X to         (0.500, 0.866, 0.000)  (same rotation)
dot(q, -q) = -1.000

Keep them normalized

Only unit quaternions are rotations. After many multiplications, rounding drifts the length away from 1, and the object starts to scale or skew. Renormalizing is four multiplies and a square root, so engines do it whenever they combine rotations (and you should after integrating angular velocity).

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>

struct Quat { float w, x, y, z; };
Quat operator*(Quat a, Quat b) {
    return {a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,
            a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
            a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
            a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w};
}
float length(Quat q) { return std::sqrt(q.w * q.w + q.x * q.x + q.y * q.y + q.z * q.z); }
Quat normalize(Quat q) { float l = length(q); return {q.w / l, q.x / l, q.y / l, q.z / l}; }

int main() {
    std::cout << std::fixed << std::setprecision(7);
    // A small spin step in float, applied a million times (like 4.6 hours of frames at 60 FPS).
    Quat step{0.99999f, 0.0031f, 0.0024f, 0.0019f};
    step = normalize(step);
    Quat drift{1, 0, 0, 0}, fixed{1, 0, 0, 0};
    for (int i = 0; i < 1000000; i++) {
        drift = step * drift;
        fixed = normalize(step * fixed);
    }
    std::cout << "length without normalizing: " << length(drift) << "\n";
    std::cout << "length with normalizing:    " << length(fixed) << "\n";
}
length without normalizing: 1.0117495
length with normalizing:    1.0000000

Note: Engines disagree on the component order in memory and constructors. Unity's new Quaternion(x, y, z, w) and Godot's Quaternion(x, y, z, w) put w last; glm::quat(w, x, y, z) puts it first in the constructor; Eigen's Quaterniond(w, x, y, z) too, while Eigen and GLM store x, y, z, w in memory. Mixing them up gives a valid-looking but completely wrong rotation.

Test yourself

What does the quaternion (cos 45°, 0, sin 45°, 0) represent?

  1. 45° around Y
  2. 90° around Y
  3. 90° around X
  4. 180° around Y

With quaternions a and b, which product applies a first?

  1. a * b
  2. b * a
  3. a + b
  4. Either; quaternion multiplication commutes

How do q and -q relate?

  1. They are opposite rotations
  2. They represent the same rotation
  3. -q is not a valid rotation
  4. -q is the conjugate