Quaternions

96
Quaternions

Introduction to quaternions and rotations in 3D.

Upadate 11 December 2021: This put up became as soon as featured on HackerNews and fast retain the pinnacle plot. Please witness this hyperlink for the elephantine discussion. Minor adjustments were completed per the comments.

Here’s section of a sequence. The opposite articles are:

Here’s a mathematical sequence and the next must haves are steered: trigonometry, algebra, complex numbers, Euclidean geometry and linear algebra (matrices).

Table of Contents

Animating in 3D

A overall hiss in pc animations is rotating an object in absolutely 3D plot.
Suppose objects, spaceships and heroes tumbling and delivering complex sequences.
Here’s in most cases accomplished with an arcane mathematical object known as a quaternion.1
As an example, here is a spaceship rotating in Solidarity, a fresh game engine that is generally extinct to create mobile video games:

rotating cruiser
Role Cruiser 1 by Gamer Squid

The code to put into effect this makes spend of Solidarity’s in-constructed Quaternion, making it very succinct:

var t = Time.time * velocity;
remodel.rotation = Quaternion.Slerp(init.rotation, final.rotation, t);

In Solidarity’s UI the init and final rotations are specified by three angles, which would be then transformed into quaternions within the backend. This suggests that printing a rotation will consequence in four numbers, no longer three.

What are these four numbers? Solidarity’s rep documentation is amazingly elusive on what quaternions are. It is worth quoting it:

Quaternions are extinct to hiss rotations.

They are compact, manufacture no longer undergo from gimbal lock and would possibly maybe maybe well without hiss be interpolated. Solidarity internally makes spend of Quaternions to hiss all rotations.

They are per complex numbers and generally are no longer easy to attain intuitively. You nearly by no methodology net admission to or adjust particular individual Quaternion formulation …

Here’s a overall caveat next to the descriptions of properties:

Don’t adjust this at as soon as until quaternions interior out.

I failed to come upon quaternions in all my years of engineering, even supposing a lecturer as soon as alluded to them for the interval of a category in my masters.
They are frowned upon in favour of extra intuitive and versatile vectors and matrices.
These can moreover be extinct to calculate 3D rotations and that’s an design that I did spend in engineering, in particular in my masters.

So why then are pc game developers and animators left to fight with this vague mathematics that engineers won’t contact? Solidarity provides correct reasons: compactness (4 numbers), numerical stability (“don’t undergo from Gimbal lock”) and interpolation (easy to hunt down rotations between other rotations).2
These are valuable differentiating components in pc video games and animations, that will maybe well moreover want to compute many thousands of rotations every physique.

This sequence of posts seeks to light up quaternions so that you are surely one of those people that is conscious of them “interior out”.
Later posts will create the logical foundations for quaternions and characterize the mathematics intimately.
For the intervening time, the leisure of this put up could be an interactive review of rotation solutions in 3D.

Mathematical representations of rotations in 3D

There are two predominant easy solutions to characterize 3D rotations:

  1. Three angles and an explain.
  2. An axis with three co-ordinates and an attitude.

In both conditions four portions are extinct to characterize the rotation, but in most cases one stage of freedom is fastened.
For 3 angles, the explain is fastened. For the axis-attitude illustration, the axis is determined to private a unit dimension, so it can probably handiest exist on the unit sphere and due to this reality two numbers are ample to characterize it (latitude and longitude).
In both case, there are three final levels of freedom.

1. Three angles and an explain

Instructions: bound each and each attitude within the next explain: ψ, θ, φ.

For the gracious individual skills, spend a substantial video display.

An intuitive technique to characterize a rotation is with three separate angles. These are identified as the Euler angles after the immense mathematician Leonhard Euler.
There are an infinite sequence of various conventions for Euler angles looking on the axes and orders chosen.
For the interactive graph I in point of fact private extinct the Tait-Bryan attitude illustration, which is generally extinct in engineering.
Here is an illustration:

Tait-Bryran angles
Modified from Wikipedia

The three angles are:

  • $psi$: yaw, about the $z$ axis.
  • $theta$: pitch, about the $y’$ axis3
  • $phi$: roll, about the $x’’$ axis.

The explain extinct is yaw-pitch-roll, moreover identified as $psi$-$theta$-$phi$ or $z$-$y’$-$x’’$ or ZYX.
As an example of how the explain impacts the final rotation, here are two rotations completed with a yaw of 30° and a roll of 90°. The left makes spend of the yaw-roll explain and the gracious a roll-yaw explain.

Tait-Bryan angles
Yaw-roll (left) and roll-yaw (correct).

On the left, the cruiser first rotates 30° to the left after which rolls on its side.
On the gracious, the cruiser rolls on it side first, so that a pilot sitting interior would behold his left as up, and due to this reality the yaw rotation ends in a 30° motion upwards.
Here’s why the explain wants to be specified.

Given the explain, each and each attitude will even be extinct to create a 3×3 rotation matrix $R_{alpha}$ which represents a 2D rotation about an axis. Glimpse section 2 for extra detail.
Then the turned around vector $v_r$ is got from $v$ by multiplying each and each matrix in explain:

[v_r = R_{phi}R_{theta}R_{psi}v]

Matrix defintions

[
R_{psi} =
begin{bmatrix}
cos(psi) & -sin(psi) & 0 \
sin(psi) & phantom{+}cos(psi) & 0 \
0 & 0 & 1
end{bmatrix}
]
[
R_{theta} =
begin{bmatrix}
phantom{+}cos(theta) & 0 & sin(theta) \
0 & 1 & 0 \
-sin(theta) & 0 & cos(theta)
end{bmatrix}
]
[
R_{phi} =
begin{bmatrix}
1 & 0 & 0 \
0 & cos(phi) & -sin(phi) \
0 & sin(phi) & phantom{+}cos(phi)
end{bmatrix}
]

I’d fancy to emphasise that the above graph is dynamically generated by the utilization of this equation to update the 3D co-ordinates for the Plotly charting library.
The tip consequence’s a natural taking a gaze rotation.4
The JavaScript code will even be found here or along with your browser’s inspection instruments.

While you happen to attain be conscious the explain, the immoral will rotate about one circle of the gimbal at the time.
However what whereas you don’t be conscious it?
As an example, you growth $theta$ and $phi$ outdated to $psi$?
Return and check up on this whereas you haven’t already.
The reply is, the total gimbal rotates to the orientation the place it will maybe maybe maybe were if the rotation explain of $z$-$y’$-$x’’$ became as soon as revered.
This route can no longer be represented with the angles $psi$, $theta$ or $phi$. (It can maybe well also be with other Euler angles but that handiest shifts the hiss.)
This already illustrates surely one of many highest problems with Euler angles: it enforces unnatural constraints.

To gaze how this would possibly maybe maybe create complexity, expend into account the interpolation hiss within the initial GIF of this put up.
Given the angles for the first and final rotation, how would you rep the rotation at the guts level?

cruiser static frames - missing middle

First create a circle that connects the nostril of the cruiser from its starting up plan to its final plan.
Then for each and each level on the arc of the circle, rep some $psi$, $theta$ and $phi$ applied in that explain that will consequence in a rotation to that level.
This requires adjusting three angles simultaneously.
One can factor in an algorithm the place you alter $psi$, then $theta$ then $phi$ and if the level doesn’t descend on the circle the place it’s alleged to lope, originate from the originate at $psi$ again.
An even bigger algorithm is equipped under, but it indubitably is unruffled constrained by the same underlying route of.
We’ll witness quickly that the quaternion algorithm is powerful, powerful simpler.

  1. The spend of the interior product: $cos(alpha) = vec{p}_0 cdot vec{p}_1 = x_1 x_2 + y_1 y_2 + z_1 z_2 $
  2. The equation of the circle is $vec{p}_t = rcos(alpha t)hat{x} + rsin(alpha t)hat{y}$
    • Elaborate $r = lvert vec{p}_0 rvert = lvert vec{p}_1 rvert $
    • Elaborate $hat{x} = frac{1}{r}vec{p}_0 $
    • Calculate $hat{y}$ from $vec{p}_1 = rcos(alpha)hat{x} + rsin(alpha)hat{y}$

    We can spend $t=0.5$ to hunt down the guts vector.

  3. With (2) there’s ample info to create the animation, but what if we need the angles?
    This requires solving 3 extremely non-linear trigonometric equations from $p_t=R_{phi}R_{theta}R_{psi}p_0$.
    An replacement is to calculate an axis-attitude rotation matrix with $hat{n} = hat{x} instances hat{y}$ and $theta = alpha t$. Then compare terms with the Euler rotation matrix.

One other hiss comes from gimbal lock.
Here’s no longer a hiss when the rotations are enforced, which is the hiss in animations.
However going the unsuitable design, the place rotations want to be calculated from accelerations and velocities – as is generally the case in physics problems – here is a predominant hiss.
In particular, when the pitch is 90°, yaw and roll switch, and this provides ample ambiguity within the equations to inject valuable numeric instability. (The same occurs at a 90° attitude for yaw and roll but handiest the guts attitude causes a hiss.)
For that reason, Euler angles ought to by no methodology be extinct in physics simulations – I squawk from skills.

The emblem $omega$ is extinct to indicate an angular velocity e.g. $omega_alpha = frac{dalpha}{dt}$, measured in radians/second. In physics problems we in most cases private the angular velocity within the world physique, $omega^0$ but we need the angular velocities of the Euler angles to combine to net the Euler angles. These angular velocities are connected as follows:
[
begin{align}
vec{omega}^0
&=
omega_{psi}hat{z} + omega_{theta}hat{y}’ + omega_{phi}hat{x}” \
begin{bmatrix}
omega_{x}^0 \
omega_{y}^0 \
omega_{z}^0
end{bmatrix}
&=
omega_{psi}
begin{bmatrix}
0 \
0 \
1
end{bmatrix}
+
omega_{theta} R_{psi}
begin{bmatrix}
0 \
1 \
0
end{bmatrix}
+
omega_{phi} R_{psi}R_{theta}
begin{bmatrix}
1 \
0 \
0
end{bmatrix} \
&=
omega_{psi}
begin{bmatrix}
0 \
0 \
1
end{bmatrix}
+
omega_{theta}
begin{bmatrix}
-sin(phi) \
phantom{+}cos(phi) \
0
end{bmatrix}
+
omega_{phi}
begin{bmatrix}
cos(phi)cos(theta) \
sin(phi)cos(theta) \
-sin(theta)
end{bmatrix} \
&=
begin{bmatrix}
cos(phi)cos(theta) & -sin(phi) & 0 \
sin(phi)cos(theta) & phantom{+}cos(phi) & 0\
-sin(theta) & 0 & 1
end{bmatrix}
begin{bmatrix}
omega_{phi} \
omega_{theta} \
omega_{psi}
end{bmatrix}
end{align}
]
Invert the matrix to net the unknown Euler velocities when it comes to the identified world velocities:
[
begin{align}
Rightarrow
begin{bmatrix}
omega_{phi} \
omega_{theta} \
omega_{psi}
end{bmatrix}
&=
frac{1}{cos(theta)}
begin{bmatrix}
cos(psi) & sin(psi) & 0 \
-sin(psi)cos(theta) & cos(psi)cos(theta) & 0\
phantom{+}cos(psi)sin(theta) & sin(psi)sin(theta) & 1
end{bmatrix}
begin{bmatrix}
omega_{x}^0 \
omega_{y}^0 \
omega_{z}^0
end{bmatrix}
end{align}
]
This expression is undefined for $costheta = 0$, which occurs at $theta = nfrac{pi}{2} ;, n in mathbb{Z}$.
Here’s the place gimbal lock occurs.

Concluding this section, now we private found that Euler angles are intuitive and work neatly for static programs.
On the opposite hand they achieve no longer seem to be suited to dynamic programs, whether or no longer that be via interpolation or numerical integration.
Thankfully the next design does work neatly within the latter case.

2. An axis and an attitude

Instructions: bound the α and β sliders to change the fashioned vector. Plod θ to rotate in a circle spherical the fashioned vector.

q = +1.000 + 0.000i + 0.000j + 0.000ok

For the gracious individual skills, spend a substantial video display.

Showcase that every and each level on the circle will even be reached twice: via the clockwise rotation or via the anti-clockwise rotation.
Here’s identified as the double cover property.

There are extra than one ways to calculate the axis-attitude illustration.
This graph makes spend of a quaternion.
Glimpse the source code here or along with your browser’s inspection instruments.

What’s a quaternion? Here is a mathematical definition:

Definition: Quaternion
/kwəˈtəːnɪən/

A quaternion is a sequence of the form $$s + xi+yj + zk ; ; ; s, x, y, z in mathbb{R}$$
the place the premise formulation $i$, $j$ and $ok$ obey the next solutions of multiplication:
$$i^2 = j^2 = ok^2 = ijk = -1 ;,; ij=ok ;,; ji=-ok$$

It can maybe well be unparalleled that $ij=ok$ but $ji=-ok$, but this would possibly maybe maybe maybe never be comely after the Euler angles section.
3D rotations depend on explain and due to this reality any mathematics that represents them must depend on explain.
Portion 3 will provide extra bodily justifications for this abstract definition.

The quaternion is calculated from the fashioned vector and $theta$ as follows:

[begin{aligned}
hat{n} &= cos(beta)cos(alpha)i + cos(beta)sin(alpha)j + sin(beta)k \
q &= cos(tfrac{theta}{2}) + sin(tfrac{theta}{2})hat{n}
end{aligned}]

The rotation is then completed with this system (proved in section 3):

[begin{aligned}
v_r &= qvq^{*}\
&= (cos (tfrac{theta}{2}) + sin (tfrac{theta}{2})hat{n})v(cos (tfrac{theta}{2})- sin (tfrac{theta}{2}) hat{n})
end{aligned}]

Euler angles are 3D which we are able to visualise, whereas quaternions are 4D that methodology we are able to no longer.
Why then ought to we protect quaternions?
Their predominant advantage comes with interpolations.
Here again is the hiss of discovering the guts rotation between the starting up and final rotations within the GIF:

cruiser static frames

Again we scheme the arc of a circle which the nostril of the cruiser will walk along.
The axis-attitude illustration is a natural match to this hiss, because this arc can itself be represented with a fashioned vector and an attitude.
Even so, the quaternion choice to the hiss is right away easy.
For this particular case of $t=0.5$, calculate the quaternion:

[q_{0.5} = frac{q_{0.0} + q_{1.0}}{2}]

and apply the rotation system. Done.

Customarily the expression for $q_t$ is extra complex. However I hope this case provides a approach of the vitality of quaternions.

Elaborate

The spend of quaternions for 3D rotations is a in point of fact suited preference for animation tool.
They are in point of fact an array of 4 numbers with the fashioned solutions for addition and subtraction and some particular solutions for multiplication. Encode that, and also you net rotation capabilities and stateless, mercurial, interpolations nearly at no cost.

I hope this put up has illuminated some of their properties and advantages.
While you happen to fancy to learn extra, the leisure of the sequence will magnify extra on the mathematics of quaternions.

  • Portion 2 describes rotations in 2D. It describes complex numbers, which is able to be regarded as a simpler form of quaternion.
  • Portion 3 describes the fundamentals of quaternions and their mathematics. About a proofs of their properties are given.
  • Portion 4 focuses on interpolation.
    An interactive graph with a stick aeroplane moderately than the Solidarity plot cruiser is provided.

To net basically the most out of this sequence, you would possibly maybe maybe well like to be cheerful with trigonometry, algebra, complex numbers, Euclidean geometry and linear algebra (matrices).
This maths became as soon as coated in my first year of engineering.

This sequence is the model I’d private loved to gaze.
After I first learnt about quaternions I discovered that I had to refer to many sources to attain them successfully.
When it comes to each and each source started with a myth of an Irish mathematician, a bridge, and an epiphany that caused him to prick the elementary system of quaternions into the stone. It’s a nice account but it indubitably is a confusing one to inaugurate with.
Why did he private this epiphany? What “magic” did he resolve that day and would possibly maybe maybe well we moreover?
In section 3 I attain state this account, but at a degree the place ample mathematics has been mentioned so we are able to moderately approximate the mathematician’s thoughts that day. Instead I selected to guide with a sure account; one about why quaternions are unruffled relevant 178 years later. I hope this became as soon as most traditional.

This sequence is written from the attitude of an engineer.
I strive to introduce solutions and provide an explanation for them in as intuitive a approach as likely.
Mathematical proofs are handiest completed for identities the place that is complex.
I moreover attain no longer explore how quaternions match into the overall context of mathematical fields and algebras,
or extra overall variations of quaternion algebra.

Identical rotations would possibly maybe maybe well moreover be accomplished with other formulas, particularly the Rodrigues’ formulas and with Pauli matrices.
I will give the formulas without going into detail; here is handiest to compare kinds.

The Rodrigues’ formulas are as follows:

[begin{aligned}
vec{v}_r &= cos theta vec{v}+
sin theta (hat{n} times vec{v})
+ (1-cos theta)(vec{v} cdot hat{n}) hat{n} \
vec{v}_r &= [I_3 + sintheta N + (1-cos theta) N^2]vec{v} ;, ; Nvec{v} = hat{n} instances vec{v}
stay{aligned}]

Showcase that $vec{v} = (x, y, z)^T equiv 0 + xi + yj + zk = v$.

The Pauli matrices system is a form of intermediate form between quaternions and the Rodrigues formulas. It makes spend of 2×2 matrices and complex numbers:

[begin{aligned}
vec{v} cdot vec{sigma} &=
begin{bmatrix}
z & x + iy \
x – iy & -z
end{bmatrix} \
U &= cos (tfrac{theta}{2}) I_2 – sin (tfrac{theta}{2})(ihat{n} cdot vec{sigma}) \
vec{v}_r cdot vec{sigma} &= U(vec{v} cdot vec{sigma} ) U^dagger
end{aligned}]

Here again is the quaternion system:

[begin{aligned}
v_r &= qvq^{*}\
&= (cos (tfrac{theta}{2}) + sin (tfrac{theta}{2})hat{n})v(cos (tfrac{theta}{2})- sin (tfrac{theta}{2}) hat{n})
end{aligned}]

These are four various formulas which would be per four various branches of mathematics (Euclidean geometry, linear algebra and complex numbers, quaternions) with extra than one various forms of multiplications (scalar multiplication, quaternion multiplication, dot products, vector depraved products and matrix multiplication), but these formulas all hiss the same bodily rotation and can consequence in same vectors $vec{v}_r$.

For a comparability of all formulas in Julia, please witness this repository: Rotations.jl.

Quaternions are highest for interpolations and due to this reality animations.
However any of those solutions will work for physics simulations.
In my thought, I in point of fact private efficiently extinct the Rodrigues matrix system on simulations of complex 3D robots.

It’s easy to calculate the fashioned vector and attitude from angular velocities.
An object with an angular velocity $vec{omega}$ rotates about an axis parallel to $vec{omega}$. So the fashioned vector is $hat{n} = frac{vec{omega}}{lvert vec{omega} rvert}$. $theta$ is a measure of the magnitude of this rotation: $ theta = lvert vec{omega} rvert Delta t = sqrt{ omega_x^2 + omega_y^2 + omega_z^2 }Delta t $. Then apply any of the axis-attitude formulas.

References

There are an infinite sequence of sources I extinct to learn about quaternions.
Each and each provides extra detail in some plot, whether or no longer or no longer it be animations, mathematical formulas, or visualisations.



Knowasiak
WRITTEN BY

Knowasiak

Hey! look, i give tutorials to all my users and i help them!