With the **Euler angles** the foundations for the calculation of the rotation of bodies in three-dimensional spaces were founded. However, it was later discovered that **Hamilton’s quaternions** are a more efficient tool for studying the rotation mode of bodies. In this article we will see what quaternions are, how they are calculated and how they apply to the rotation of a body, also helping us in this case with some Python code.

## Hamilton’s Quaternions

**Quaternions** were devised by the mathematician **Hamilton **(1805-1865) to extend the functionality of complex numbers into a four-dimensional system.

Complex numbers are generally denoted by notation

where a is the real part, b is the imaginary component while i is the imaginary unit defined as the square root of -1

Quaternions extend the concept of complex numbers, and then two more -1 symbols are added:

where w is the real part, and i, j, k denote the three imaginary units, and x, y, z denote the three imaginary components. To make things easier you can simply write:

where w is the scalar component and v = (x, y, z) is the vector of the imaginary components.

## The algebra of quaternions

The following basic rules are based on the algebra of quaternions:

Furthermore, given two quaternions q_{1} and q_{2}:

the **sum of the two quaternions** is defined as follows:

while the **product of the two quaternions** takes place in this way:

In the notation with the vector v we have a more synthetic expression

where v1 ∙ v2 is the scalar product and v1 × v2 is the vector product.

Other important definitions for quaternion algebra are the conjugate, the norm and the inverse of a quaternion.

The **conjugate of a quaternion **is denoted by q * and is defined as:

If we multiply a quaternion with its conjugate we have:

The length or **norm of a quaternion **is instead defined as:

Finally for every quaternion, except q = 0, there is an **inverse** defined as:

The last algebraic operation is the division between two quaternions, which can be obtained by multiplying the first quaternion by the inverse of the second

A final consideration in this regard is that while complex numbers constitute an algebraic field, quaternions instead constitute an algebraic body. This is because for quaternions the commutative property of the product does not hold and therefore q_{1} x q_{2} is different from q_{2} x q_{1}.

## Quaternions as a tool for calculating the rotations of a body around an arbitrary axis

According to Euler’s theorem, any rotation or sequence of rotations of a rigid body around a fixed point is equivalent to a single rotation of an angle θ around a certain axis (called the Euler axis) passing through this fixed point.

The Euler axis is normally represented by a vector unit (unit vector) . Therefore any rotation in 3 dimensions can be represented as a combination of a unit vector and a scalar value θ.

A rotation of an angle θ around an axis defined by the unit vector

Similarly to how we did with Euler angles and the rotation matrix R, which can be applied to an ordinary vector p:

We can therefore indicate with **R(θ,p)** the rotation of a vector p by an angle θ around the axis indicated by the unit vector u, as we have already seen in the previous article on Euler angles.

The same rotation can be represented with a **Hamilton quaternion**:

also representable in form

with

associating the various terms to the angles of rotation

where theta is the rotation angle and are the director cosines of the rotation axis indicated by the unit vector u..

Furthermore, it is possible to obtain a result of the Rotation matrix used with Euler angles, using the quaternion q, calculating the conjugation of the vector p_{0} with q. We thus obtain the new vector p_{1} which is the result of the rotation.

with

Applying several theorems and defining a **pure quaternion**:

and a **unitary quaternion**

you find that

Further expanding the second term a matrix is obtained

Given the rotation matrix described above, it is possible to go back to the corresponding quaternion with a few steps. The trace of the matrix R (sum of the diagonal elements) is calculated:

this is because the quaternion is unitary

therefore

The other components x, y, z are calculated in a similar way.

## Rotation with quaternions in Python

Now that we have seen that it is possible to perform rotation calculations with quaternions and which are the mathematical expressions to use, let’s start implementing everything in Python.

First we need to calculate the quaternion conjugate.

```
def q_conjugate(q):
w, x, y, z = q
return (w, -x, -y, -z)
```

We now have all the elements to carry out the multiplication

In fact P is none other than the pure quaternion obtained, using the vector v to rotate for the three imaginary terms and the real part w equal to zero.

So in Python we can implement like this:

```
def qv_mult(q1, v1):
q2 = (0.0,) + v1
return q_mult(q_mult(q1, q2), q_conjugate(q1))[1:]
```

As we can see in the function, it is necessary to use the multiplication between quaternions, and therefore we must implement it in Python using the equations previously performed mathematically.

```
def q_mult(q1, q2):
w1, x1, y1, z1 = q1
w2, x2, y2, z2 = q2
w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2
x = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2
y = w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2
z = w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2
return w, x, y, z
```

Moreover, if we have a sequence of multiple rotations, as it was possible with Euler to multiply among them the rotation matrices R, in the same way the quaternions corresponding to the single rotations are multiplied among them. The resulting quaternion will be equivalent to the total rotation.

## Conversion from Euler angles to quaternions and vice versa

Another very useful and common operation is that of passing from Euler’s formulation to that of quaternions. It is therefore possible, knowing the Euler angles (), find the corresponding quaternion q.

For example, for the Euler angles in an XYZ convention, we obtain the quaternion q corresponding to this rotation with the following expression:

Which in Python can be expressed in the following function:

```
def euler_to_quaternion(phi, theta, psi):
qw = m.cos(phi/2) * m.cos(theta/2) * m.cos(psi/2) + m.sin(phi/2) * m.sin(theta/2) * m.sin(psi/2)
qx = m.sin(phi/2) * m.cos(theta/2) * m.cos(psi/2) - m.cos(phi/2) * m.sin(theta/2) * m.sin(psi/2)
qy = m.cos(phi/2) * m.sin(theta/2) * m.cos(psi/2) + m.sin(phi/2) * m.cos(theta/2) * m.sin(psi/2)
qz = m.cos(phi/2) * m.cos(theta/2) * m.sin(psi/2) - m.sin(phi/2) * m.sin(theta/2) * m.cos(psi/2)
return [qw, qx, qy, qz]
```

Same thing we can do in reverse. Knowing the terms of the quaternion, obtain the Euler angles in an XYZ convention.

Which can be implemented in Python in the following function:

```
def quaternion_to_euler(w, x, y, z):
t0 = 2 * (w * x + y * z)
t1 = 1 - 2 * (x * x + y * y)
X = m.atan2(t0, t1)
t2 = 2 * (w * y - z * x)
t2 = 1 if t2 > 1 else t2
t2 = -1 if t2 < -1 else t2
Y = m.asin(t2)
t3 = 2 * (w * z + x * y)
t4 = 1 - 2 * (y * y + z * z)
Z = m.atan2(t3, t4)
return X, Y, Z
```

## Example – the rotation of a point in space

We will now take the same example we did with Euler’s transformations, but this time using quaternions instead of the rotation matrix R.

The simplest example of application of what we have already seen in the article is the rotation of a point located in a coordinate space (X, Y, Z). A point in space can be represented by a 3-element vector that characterizes its values on the three coordinate axes.

So for our example, we will start from a simple point on the X axis described by the following vector. Which is the same as the example with Euler’s angles.

Let’s express the vector as a tuple this time:

```
v1 = (1,0,0)
```

Now to obtain the quaternion that is equivalent to the same rotation of the example with the Euler angles, we will use the latter and convert them into the corresponding quaternion using the function we have just defined. So let’s first define the three Euler angles and then convert them into the quaternion whose terms we are going to visualize.

```
phi = m.pi/2
theta = m.pi/4
psi = m.pi/2
q = euler_to_quaternion(phi, theta, psi)
print("w =", q[0])
print("x =", q[1])
print("y =", q[2])
print("z =", q[3])
```

By executing the following quaternion is obtained

w = 0.6532814824381883 x = 0.27059805007309845 y = 0.6532814824381882 z = 0.2705980500730985

Now let’s do the multiplication between vector and quaternion

```
v2 = qv_mult(q,v1)
print(np.round(v2, decimals=2))
```

And we will get the same vector we obtained in the example of Euler’s angles.

[ 0. 0.71 -0.71]

Let’s see the result of our rotation by plotting the position of the vector (which describes the point) before and after the rotation on a graph with Cartesian axes.

```
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Cartesian axes
ax.quiver(-1, 0, 0, 3, 0, 0, color='#aaaaaa',linestyle='dashed')
ax.quiver(0, -1, 0, 0,3, 0, color='#aaaaaa',linestyle='dashed')
ax.quiver(0, 0, -1, 0, 0, 3, color='#aaaaaa',linestyle='dashed')
# Vector before rotation
ax.quiver(0, 0, 0, 1, 0, 0, color='b')
# Vector after rotation
ax.quiver(0, 0, 0, 0, 0.71, -0.71, color='r')
ax.set_xlim([-1.5, 1.5])
ax.set_ylim([-1.5, 1.5])
ax.set_zlim([-1.5, 1.5])
plt.show()
```

By running the code you will get the graphical representation.

From here you can then move on to the rotation of lines, geometric figures and three-dimensional objects. All at the basis of the 3D engines with which many video games are developed.

## Advantages of using quaternions with respect to Euler angles

The use of quaternions instead of Euler angles when it comes to calculating the rotation in a three-dimensional space leads to some advantages. Let’s see in detail what they are.

For the calculation of a rotation with Euler angles, 9 parameters are required, while for quaternions only 4 parameters are needed.

The rotation with Euler angles consists of a sequence of elementary rotations around one of the three Cartesian axes with many possible combinations. This requires different equations and resolutions for each case. While the rotation through quaternions is unique.

Quaternion rotation is not subject to gimbal lock.

AnastasiiaHi! Seems there is a minor typo in the formula for the rotation matrix made of quaternion elements R. For element R[1][2] it should be 2yz-2wx instead of 2yz-2wz. Anyway thanks a lot! It is a very useful article!

webmasterThanks. Yes, I correct the formula.