# Quaternion

Quaternion is a type of number, just like there are integer numbers, real numbers or imaginary numbers. They are very useful for certain things such as 3D rotations (they have some advantages over using e.g. Euler angles, for example they avoid Gimbal lock, they are also faster than transform matrices etc.). Quaternions are not so easy to understand but you don't actually need to fully grasp and visualize how they work in order to use them if that's not your thing, there are simple formulas you can copy-paste to your code and it will "just work".

Quaternions are an extension of complex numbers (you should first check out complex numbers before tackling quaternions); while complex numbers can be seen as two dimensional -- having the real and imaginary part -- quaternions would be seen as four dimensional. A quaternion can be written as:

*a + bi + cj + dk*

where *a*, *b*, *c* and *d* are real numbers and *i*, *j* and *k* are the basic quaternion units. For the basic units it holds that 

*i^2 = j^2 = k^2 = ijk = -1*

**Why four components and not three?** Simply put numbers with three components don't have such nice properties, it just so happens that with four dimensions we get this nice system that's useful.

Operations with quaternions such as their multiplication can simply be derived using basic algebra and the above given axioms. Note that **quaternion multiplication is non-commutative** (*q1 * q2 != q2 * q1*), but it is still associative (*q1 * (q2 * q3) = (q1 * q2) * q3*).

A **unit quaternion** is a quaternion in which *a^2 + b^2 + c^2 + d^2 = 1*.

A **quaternion negation** (*q^-1*) is obtained by multiplying *b*, *c* and *d* by -1.

## Rotations

Only unit quaternions represent rotations. 

Rotating point *p* by quaternion *q* is done as

*q^-1 * (0 + p.x i + p.y j + p.z k) * q*

Rotation quaternion can be obtained from axis (*v*) and angle (*a*) as

*q = cos(a/2) + sin(a/2) * (v.x i + v.y j + v.z k)*

TODO: compare to euler angles, exmaples