Skip to content

Quaternions

Quaternions are a mathematical concept that extends the idea of complex numbers to four dimensions. They are used in many fields, including computer graphics, robotics, and physics. In the context of this toolkit, they represent rotations in 3D space and are operationally equivalent to rotation matrices.

They have several advantages over rotation matrices, including:

  • They are more compact, requiring only four numbers to represent a rotation instead of nine.
  • They are more numerically stable, avoiding the gimbal lock problem.
  • They are easier to interpolate between, making them useful for animations.

Warning

Quaternions in this module perform a right-handed rotation of the vector. You will occasionally see (especially in attitude control texts) a quaternion convention that does a right-handed rotation of the coordinate system, which is a left-handed rotation of the vector.

For an excellent description of quaternions, see here; the conventions follow Markley & Crassidis (2014), and spherical linear interpolation (slerp) is the construction of Shoemake (1985).

quaternion

Quaternion representing rotation of 3D Cartesian axes

Quaternions perform right-handed rotation of a vector, e.g. rotation of +xhat 90 degrees by +zhat give +yhat

This is different than the convention used in Vallado, but it is the way it is commonly used in mathematics and it is the way it should be done.

For the uninitiated: quaternions are a more-compact and computationally efficient way of representing 3D rotations. They can also be multiplied together and easily renormalized to avoid problems with floating-point precision eventually causing changes in the rotated vector norm.

For details, see:

https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation

Notes

A quaternion is always a unit quaternion (a rotation): every constructor normalizes its result, so norm is 1 to rounding. q and -q are the same rotation but are different quaternions.

norm property

Quaternion norm (Euclidean length of the 4 components). Quaternions are kept unit, so this is 1 to rounding.

angle property

Return the angle in radians of the rotation, in [0, 2 pi)

The angle is measured about axis, right-handed. It exceeds pi when the scalar component w is negative; the same rotation is then the angle 2 pi - angle about -axis.

Returns:

Type Description
float

Angle in radians of the rotation

axis property

Return the axis of rotation as a unit vector

The identity (no rotation) has no axis; [1, 0, 0] is returned for it.

Returns:

Type Description
NDArray[float64]

3-element array representing the axis of rotation as a unit vector

x property

X component of the vector part

y property

Y component of the vector part

z property

Z component of the vector part

w property

Scalar component (cosine of half the rotation angle)

from_axis_angle(axis, angle) staticmethod

Quaternion representing right-handed rotation of vector by "angle" radians about the given axis

Parameters:

Name Type Description Default
axis ArrayLike

3-element array representing axis of rotation (unitless direction; need not be normalized)

required
angle float

angle of rotation in radians

required

Returns:

Type Description
quaternion

Quaternion representing rotation by "angle" radians about the given axis. If the axis has (near-)zero length (norm < 1e-9) the identity is returned, whatever the angle

Raises:

Type Description
TypeError

axis is not a real numeric array-like

ValueError

axis does not have 3 elements, or axis or angle holds a NaN or infinity

from_rotation_matrix(dcm) staticmethod

Return quaternion representing identical rotation to input 3x3 rotation matrix

Parameters:

Name Type Description Default
dcm ArrayLike

3x3 rotation matrix (any real numeric array-like): orthonormal, with determinant +1

required

Returns:

Type Description
quaternion

Unit quaternion representing identical rotation to input 3x3 rotation matrix

Raises:

Type Description
TypeError

dcm is not a real numeric array-like

ValueError

dcm is not 3x3, holds a NaN or infinity, or is not a rotation matrix (dcm @ dcm.T differs from the identity by more than 1e-6 in any element, or the determinant is negative)

rotx(theta_rad) staticmethod

Quaternion representing right-handed rotation of vector by "theta" radians about the xhat unit vector

Parameters:

Name Type Description Default
theta_rad float

angle of rotation in radians

required

Returns:

Type Description
quaternion

Quaternion representing right-handed rotation of vector by "theta" radians about the xhat unit vector

Raises:

Type Description
ValueError

theta_rad is NaN or infinite

Notes

Equivalent rotation matrix:

| 1             0            0|
| 0    cos(theta)  -sin(theta)|
| 0    sin(theta)   cos(theta)|

roty(theta_rad) staticmethod

Quaternion representing right-handed rotation of vector by "theta" radians about the yhat unit vector

Parameters:

Name Type Description Default
theta_rad float

angle of rotation in radians

required

Returns:

Type Description
quaternion

Quaternion representing right-handed rotation of vector by "theta" radians about the yhat unit vector

Raises:

Type Description
ValueError

theta_rad is NaN or infinite

Notes

Equivalent rotation matrix:

|  cos(theta)     0    sin(theta)|
|           0     1             0|
| -sin(theta)     0    cos(theta)|

rotz(theta_rad) staticmethod

Quaternion representing right-handed rotation of vector by "theta" radians about the zhat unit vector

Parameters:

Name Type Description Default
theta_rad float

angle of rotation in radians

required

Returns:

Type Description
quaternion

Quaternion representing right-handed rotation of vector by "theta" radians about the zhat unit vector

Raises:

Type Description
ValueError

theta_rad is NaN or infinite

Notes

Equivalent rotation matrix:

|  cos(theta)     -sin(theta)   0|
|  sin(theta)      cos(theta)   0|
|           0               0   1|

rotation_between(v1, v2) staticmethod

Quaternion representation rotation between two input vectors

Parameters:

Name Type Description Default
v1 ArrayLike

3-element vector rotating from (any real numeric array-like)

required
v2 ArrayLike

3-element vector rotating to (any real numeric array-like)

required

Returns:

Type Description
quaternion

Quaternion of the shortest rotation from v1 to v2 (about the axis v1 x v2; the vectors need not be unit length)

Raises:

Type Description
TypeError

an input is not a real numeric array-like

ValueError

an input does not have 3 elements or holds a NaN or infinity, either vector has (near-)zero length, or the vectors point in opposite directions (the rotation axis is then not unique)

Example
import numpy as np
v1 = np.array([1, 0, 0])
v2 = np.array([0, 1, 0])
q = satkit.quaternion.rotation_between(v1, v2)
print(q * v1)
# [0, 1, 0]

to_rotation_matrix()

Return 3x3 rotation matrix representing equivalent rotation

Returns:

Type Description
NDArray[float64]

3x3 rotation matrix representing equivalent rotation

as_rotation_matrix()

Deprecated since 0.23, removed in 0.25. Use quaternion.to_rotation_matrix.

to_euler()

Return equivalent rotation as intrinsic ZYX Euler angles, returned as (roll, pitch, yaw).

The decomposition follows the aerospace convention (Tait-Bryan angles): the rotation is equivalent to first rotating by yaw about Z, then pitch about the new Y, then roll about the new X.

Returns:

Type Description
tuple[float, float, float]

(roll, pitch, yaw) in radians

Example
q = satkit.quaternion.rotz(0.1) * satkit.quaternion.roty(0.2)
roll, pitch, yaw = q.to_euler()

as_euler()

Deprecated since 0.23, removed in 0.25. Use quaternion.to_euler.

from_euler(roll, pitch, yaw) staticmethod

Create quaternion from roll, pitch, yaw Euler angles in radians (inverse of to_euler)

Parameters:

Name Type Description Default
roll float

Roll angle in radians

required
pitch float

Pitch angle in radians

required
yaw float

Yaw angle in radians

required

Returns:

Type Description
quaternion

Quaternion representing the input euler-angle rotation

Raises:

Type Description
ValueError

an angle is NaN or infinite

identity() staticmethod

The identity (no-rotation) quaternion (w=1, x=y=z=0)

normalize()

Return this quaternion normalized to unit length

Quaternions are already unit; this only removes rounding error accumulated over a long chain of products.

inverse()

Quaternion inverse: the opposite rotation. Same as conj() and conjugate(), quaternions being unit.

dot(other)

Dot product of the 4 quaternion components with another quaternion

conj()

Quaternion conjugate, which for a unit (rotation) quaternion is the inverse rotation. Same as conjugate() and inverse().

Returns:

Type Description
quaternion

Conjugate or inverse of the rotation

conjugate()

Quaternion conjugate, which for a unit (rotation) quaternion is the inverse rotation. Same as conj() and inverse().

Returns:

Type Description
quaternion

Conjugate or inverse of the rotation

slerp(other, frac)

Spherical linear interpolation between self and other

Parameters:

Name Type Description Default
other quaternion

Quaternion to perform interpolation to

required
frac float

fractional distance from self (0) to other (1). It is not clamped: a value outside [0, 1] extrapolates along the same arc

required

Returns:

Type Description
quaternion

Quaternion representing interpolation between self and other, along the shorter of the two arcs (other and -other are the same rotation; the nearer one is used)

Raises:

Type Description
ValueError

frac is NaN or infinite

__eq__(other)

True when other is a quaternion with exactly the same four components (no tolerance)

q and -q are the same rotation but compare unequal; so do two quaternions that differ by rounding. To compare rotations use q1.isclose(q2) or q1.angle_to(q2).

angle_to(other)

Rotation angle between this orientation and another, radians in [0, pi]

The angle of the rotation self.conj() * other that takes one to the other. q and -q are the same rotation, so q.angle_to(-q) is 0.

Parameters:

Name Type Description Default
other quaternion

The other orientation

required

Returns:

Type Description
float

Angle between the two rotations, radians in [0, pi]

Example
import math
q1 = satkit.quaternion.rotz(math.radians(10))
q2 = satkit.quaternion.rotz(math.radians(40))
print(math.degrees(q1.angle_to(q2)))
# 30.0 (to rounding)

isclose(other, *, atol=1e-12)

True when other is the same rotation to within atol radians

Compares rotations, not components: q and -q are the same rotation and are close (unlike ==, which compares the four components exactly).

Parameters:

Name Type Description Default
other quaternion

The rotation to compare with

required
atol float

Largest angle_to(other), radians, still counted as the same rotation. Default 1e-12

1e-12

Returns:

Type Description
bool

self.angle_to(other) <= atol

Raises:

Type Description
ValueError

atol is negative, NaN or infinite

Example
q = satkit.quaternion.rotx(0.3)
print(q.isclose(satkit.quaternion(-q.w, -q.x, -q.y, -q.z)))
# True

to_axis_angle()

Rotation axis and angle, the inverse of from_axis_angle

The same values as the axis and angle properties: quaternion.from_axis_angle(*q.to_axis_angle()) is q.

Returns:

Type Description
tuple[ndarray, float]

Unit rotation axis (3-element array; [1, 0, 0] for the identity) and the right-handed angle about it in radians, in [0, 2 pi)

Example
axis, angle = satkit.quaternion.rotz(0.5).to_axis_angle()

to_array()

The four components as an array in the order [w, x, y, z] (scalar first), the inverse of from_array

Returns:

Type Description
ndarray

4-element float64 array [w, x, y, z]

Example
print(satkit.quaternion().to_array())
# [1. 0. 0. 0.]

from_array(arr) staticmethod

Quaternion from an array of its four components in the order [w, x, y, z] (scalar first), the inverse of to_array

The same as quaternion(w, x, y, z): the components are scaled to unit norm.

Parameters:

Name Type Description Default
arr ArrayLike

4 components [w, x, y, z] (any real numeric array-like: numpy array, list or tuple)

required

Returns:

Type Description
quaternion

Unit quaternion along arr

Raises:

Type Description
TypeError

arr is not a real numeric array-like

ValueError

arr does not have 4 elements, holds a NaN or infinity, or is all zeros

Example
q = satkit.quaternion.from_array([1.0, 0.0, 0.0, 0.0])

__hash__()

Hash of the four components, consistent with ==

Example
import math
q1 = satkit.quaternion.rotz(math.radians(0))
q2 = satkit.quaternion.rotz(math.radians(90))
q_mid = q1.slerp(q2, 0.5)
print(f"Mid-rotation angle: {math.degrees(q_mid.angle):.1f} deg")
# Mid-rotation angle: 45.0 deg

__init__(w, x, y, z)

__init__() -> None
__init__(w: float, x: float, y: float, z: float) -> None

Return the unit quaternion along the input (w,x,y,z) values

With no arguments, return the identity quaternion. Otherwise pass all four components positionally (keywords are not accepted); they are scaled to unit norm, so quaternion(2, 0, 0, 0) is the identity.

Parameters:

Name Type Description Default
w float

Scalar component of the quaternion

required
x float

X component of the quaternion

required
y float

Y component of the quaternion

required
z float

Z component of the quaternion

required

Raises:

Type Description
TypeError

the number of arguments is neither 0 nor 4, or a component is not a real number

ValueError

all four components are zero, or one is NaN or infinite

Example
# Identity quaternion (no rotation)
q = satkit.quaternion()

# 90 degree rotation about z-axis
import math
q = satkit.quaternion.rotz(math.radians(90))

__mul__(other)

__mul__(other: quaternion) -> quaternion
__mul__(other: npt.NDArray[Any] | Sequence[float] | Sequence[Sequence[float]]) -> npt.NDArray[np.float64]
__mul__(other: quaternion) -> quaternion

Multiply by another quaternion to concatenate rotations

Notes
  • Multiply represents concatenation of two rotations representing the quaternions. The left value rotation is applied after the right value, per the normal convention

Parameters:

Name Type Description Default
other quaternion

quaternion to multiply by

required

Returns:

Type Description
quaternion

Quaternion representing concatenation of the two rotations

__mul__(other: npt.NDArray[Any] | Sequence[float] | Sequence[Sequence[float]]) -> npt.NDArray[np.float64]

Multiply by a vector to rotate the vector

Parameters:

Name Type Description Default
other NDArray | Sequence[float] | Sequence[Sequence[float]]

3-element vector to rotate, or Nx3 array of vectors to rotate (any real numeric array, list or tuple; integers are converted to float64). A scalar is not a vector: q * 2.0 raises TypeError

required

Returns:

Type Description
NDArray[float64]

3-element array representing rotated vector or Nx3 array of rotated vectors

Example
xhat = np.array([1,0,0])
q = satkit.quaternion.rotz(np.pi/2)
print(q * xhat)
# [0, 1, 0]