Calculate rotation using Quaternions

Memo for myself about quaternions (when used to calculate rotation in 3D space).

A quaternion is an extension of the complex numbers. In the context of a spatial rotation, it's a vector of dimension 4 encoding a rotation angle in radians around an axis in 3D. The advantages of using quaternions over rotation matrices are: they use less memory, they are more numerically stable, and they are easier to use.

Structure to memorise a quaternion:

A default quaternion corresponding to no rotation has values \((0, 0, 0, 1)\). Using the conventions: same handness for the rotation as for the coordinates system; matrix stored by row. Creating a quaternion from a rotation axis and an angle can be done as follow:

Converting a rotation matrix to a quaternion can be done as follow:

Converting a quaternion to a rotation matrix can be done as follow:

Adding two quaternions can be done as follow:

Substracting two quaternions can be done as follow:

The conjugate of a quaternion (the inverse rotation) can be calculated as follow:

Applying a quaternion to a vector can be done as follow:

Applying the conjugate of a quaternion to a vector can be done as follow:

The rotation angle of the quaternion can be obtained as follow:

The rotation axis of a quaternion can be calculated as follow:

The rotation angle of a quaternion can be increased as follow:

Unit test to check that the implementation is correct:

2022-07-25
in All, C programming,
101 views
Copyright 2021-2024 Baillehache Pascal