
How Quaternions encode rotations: derivation and sample code - CarolineW
http://loopspace.mathforge.org/HowDidIDoThat/Codea/Quaternions/
======
jacobolus
Anyone interested in such topics should check out geometric algebra, a.k.a.
Clifford algebra. Start with
[http://geocalc.clas.asu.edu/pdf/OerstedMedalLecture.pdf](http://geocalc.clas.asu.edu/pdf/OerstedMedalLecture.pdf)

Matrices and trigonometry are in my opinion a pedagogically, conceptually, and
practically poor way of understanding and using quaternions; furthermore,
cross products (and the associated confusion about a right hand rule and polar
vs. axial vectors and so on, not to mention a total failure to generalize to
higher dimensions) need to vanish from the earth.

More generally, this is a topic that should be explained first using pictures,
ideally interactive ones. The algebraic manipulations to formally prove what
the pictures explain visually should just fill in the bookkeeping details.

Finally, perhaps the most important reason geometric (Clifford) algebras
should be used for pedagogy, even if you plan to write code which only uses
quaternions per se, is that they make the “sandwich” multiplication of versors
as operators on vectors completely obvious as composition of reflections.

~~~
grondilu
Say what you want about geometric algebra, if it has a least one merit, it's
that it makes rotations in 3D space and their link with quaternions very
simple to understand.

Also check out my implementation in Perl 6:

[https://github.com/grondilu/clifford](https://github.com/grondilu/clifford)

With it, quaternions become:

    
    
        use Clifford;
    
        constant I = @e[1]*@e[2];
        constant J = @e[2]*@e[3];
        constant K = @e[1]*@e[3];
        
        say I² == J² == K² == I*J*K == -1;

~~~
logfromblammo
The subalgebra of 3D Clifford using the scalar and the 2-blades represents
quaternions.

The subalgebra using the pseudoscalar and the 1-blades can _also_ represent
quaternions.

You have to be careful using other people's implementations, because certain
operations are anticommutative, so sign conventions and operand ordering
matters a lot more. For instance, choosing whether K is defined as e3 * e1
rather than e1 * e3 depends on whether your base vectors square to 1 or -1.

Geometric Algebra is cool. It lets you say things like "the intersection of
two spheres that don't touch is a circle with negative radius." You can't even
represent a circle with negative radius in regular geometry.

~~~
grondilu
> You have to be careful using other people's implementations, because certain
> operations are anticommutative, so sign conventions and operand ordering
> matters a lot more. For instance, choosing whether K is defined as e3 * e1
> rather than e1 * e3 depends on whether your base vectors square to 1 or -1.

Sure. For my implementation I thought a lot about how to deal with signatures
and stuff. It's technically easy but making it simple and elegant is not
obvious. I first thought about defining a @signature array, but then it
occurred to me that it's much simpler to create two infinite spaces : one
euclidean and one anti-euclidean. Later I've learned that Hestenes and others
have considered this as well, they called it the _mother of all geometric
algebras_ , or _universal geometric algebra_ [1]. Conveniently, Perl 6 deals
with infinite lists very well, so it was very appropriate.

So in my implementation, @e[$i]² is +1 for all $i. If you want vectors with
negative squares, use the @ē basis.

With geometric algebra, there are indeed several ways to represent
quaternions. In fact there are several ways to represent complex numbers as
well. I don't think it's a pitfall. As long as notations are clear and simple,
it should be fine, I think.

1\.
[https://en.wikipedia.org/wiki/Universal_geometric_algebra](https://en.wikipedia.org/wiki/Universal_geometric_algebra)

~~~
logfromblammo
No, not a pitfall. it is more like a small pothole in the road: the problem is
easily avoided if you already know that it exists.

------
gravypod
For anyone who hasn't been exposed to this problem before, like me, there are
countless applications for this sort of mathematical operations in game
development.

Back a few years ago a friend and I were attempting to write a game engine. We
hit many road blocks but what often killed us was fixing gimble lock. This
isn't an issue for many things like FPSs or side scroller but when you get
into the realm that we wanted to tackle (first person space flight) it becomes
a challenge.

Quaternions, from my position as the ultimate laymen, take up the slack that
Euler coordinates/angles have. The issue comes from rotating an object. Once
the object is upside down, it's coordinate system stops working as you would
expect. If you are head-to-floor upside down then your up relative to the
world is down. When applying rotations that are based on shifts in pitch, yaw,
and roll it is difficult to have correct behavior.

If instead of this, you implement quaternion rotations for all objects, this
entire class of headache melts away. The problem is finding a good explanation
of how this works or even yet how to implement it. It's what's stopped me dead
in my tracks many times as the implementations often available still have many
bugs (when in Space Engineers if you rotate your cursor a circle quickly
you'll slowly rotate your character, this is a common bug in many
implementations I've found)

I'm definitely going to read through all of this when I get back from uni
today.

PS: Mathematicians/dark arts practicers, if I'm incorrect about anything I've
said here please let me know and point me to where I can learn more

~~~
devbug
How familiar are you with the complex plane?

It helped me a lot to be explained quaternions starting from the complex
plane. More specifically, by constructively inspecting their properties.
There's a great interactive article that gets the pedagogy of teaching such a
complex concept (pun definitely intended). Unfortunately, I can't seem to dig
it up.

I recall the author's blog using all kinds of CSS and/or WebGL trickery to
make 3d backgrounds – anyone know which blog I'm referring to?

~~~
kalid
Steven Wittens:

[https://acko.net/blog/animate-your-way-to-
glory/](https://acko.net/blog/animate-your-way-to-glory/)

[https://acko.net/blog/animate-your-way-to-glory-
pt2/](https://acko.net/blog/animate-your-way-to-glory-pt2/)

------
duiker101
This seems a very good and in-depth. I recently had to learn a bit of this
stuff and coming from very basic math Quats are a bit of funny concept at
first. This video does an amazing job at explaining what they are
[https://www.youtube.com/watch?v=4mXL751ko0w](https://www.youtube.com/watch?v=4mXL751ko0w)
and the pro/cons over euler angles. The whole channel has some pretty good
resources for anyone looking for a "soft approach" at math.

------
chombier
Quaternions are much easier to grasp once you are familiar with basic Lie
group theory, in particular the adjoint representation of the group over its
Lie algebra.

Then the link with rotations becomes obvious and it gets very easy to
transport geometric operations from the unit sphere to the rotation group
(spherical linear interpolation, averaging, etc...)

~~~
munchbunny
Unless I'm missing something, this feels like trying to understand a less
complicated thing by first understanding a more complicated thing?

~~~
chombier
Sometimes this is the math way ;)

More seriously, Lie group theory puts the light exactly on the shared
structure between quaternions and rotations (both are smooth groups related in
some way) and ignore the secondary details, so you spend time understanding
what matters.

It may be more abstract, but you get more from your efforts in my opinion.

------
Sharlin
I haven't thought about it before but once you start thinking of complex
numbers as "numbers that want to turn" (every unit complex number is
isomorphic to a rotation on R^2), the concept of quaternions analoguously
representing rotations in R^3 becomes pretty intuitive even if you don't quite
grok the details.

~~~
Bootvis
Hmm, but I would think that a quaternion represents a rotation in R^4 (for
which I lack intuition).

~~~
uryga
===== EDIT: this is mostly wrong - see jblow's reply. Sorry for misleading you
into thinking I know what I'm talking about :D =====

I think of it like this: a complex number represents a rotation in a plane.
You need two "coordinates" to do that. 2d has one plane, but 3d has two planes
- think about how an anti-air cannon rotates left-right and up-down. So, if
we've got two rotations to represent, you must need two complex numbers -
that's four "coordinates", or one quaternion.

~~~
chombier
> but 3d has two planes

Why not 3 planes?

~~~
uryga
Okay, my wording wasn't the best here. 3d doesn't "have" 2 planes. But, for
some reason, you can look in any direction in 3d by turning in two planes.
Test it yourself: turning your head left-right is rotation in one plane,
turning it up-down is rotation in the other plane. here's my shot at
illustrating this:
[https://goo.gl/photos/Cxt7KPbos5o2QnkD9](https://goo.gl/photos/Cxt7KPbos5o2QnkD9)

to be completely honest, I'm not sure if this intuition is correct. But it
seems to make sense

~~~
jblow
It's correct that you can look in any direction with only two planes, but
that's not enough; you need to be able to control your orientation around that
final axis. You need 3 planes for that (3 "rotational degrees of freedom").
The idea that a quaternion is somehow two complex numbers is wrong.

~~~
chombier
I think you can do that using two rotation axis only (cf. proper Euler
angles).

And quaternions _are_ made of two complex numbers.

edit: typo.

~~~
Kristine1975
_> And quaternions are made of two complex numbers._

I don't pretend to grok quaternions (I only use them), but I'm fairly sure a
quaternion consists of three imaginary numbers plus a real number.

~~~
chombier
Sure, but the way they play together can also be expressed by the means of two
complex numbers (which makes 4 real numbers in total).

~~~
jblow
This is not true. You can't factor a quaternion into two complex numbers.
Please don't spread misinformation.

------
EllipticCurve
Nice, lots of detailed explanation!

For people interested, to use them in a C/C++ context, feel free to have a
look at my Quaternion-Library.

[https://github.com/MauriceGit/Quaternion_Library](https://github.com/MauriceGit/Quaternion_Library)

~~~
jordigh
This looks like C. Why do you call it "C/C++"? It could just as well be
C/ObjC, right?

~~~
generic_user
C and C++ share the same memory model and can be called quite easily form each
other with the use of an 'extern "C"'.

It's a common practice to write libraries in C for flexibility, (many
languages can ingest C) and use the 'extern "C"' for use in C++ code.

You can also write a thin C++ class wrapper for a more native object oriented
interface.

~~~
jordigh
But all of this is true for ObjC too. How come people write C/C++ to describe
pure C code but not C/ObjC? C is as much of a subset of ObjC as it is a subset
of C++.

It's funny people don't do this as much with other languages. For example,
nobody describes pure Javascript as "js/html" even though you can have lots of
js inside HTML code.

~~~
generic_user
Its an interesting point.

C is actually part of of the C++ standard. Within the ISO C++11 standard there
is the C99 standard with some adjustments and exclusions. The integration is
quite tight. So one can say C/C++ with some clarity.

Library writers often go thorough a lot of work to write extensive object
oriented interfaces around C libraries. And they intend that the user use the
C++ version not just import the C version in there C++ code. So in that case
it is a necessity to use C/C++ because there are two separate interfaces.

In the general case I would guess that 'most' C programmers write some C++ and
vise versa. So you have a very large overlap of C/C++ programmers. Objective C
on the other hand is probably a significantly smaller group and is simply not
big enough for C/C++ communities to think to much about.

~~~
jordigh
> _In the general case I would guess that 'most' C programmers write some C++
> and vise versa._

That's not what I've seen. People usually either write C++ exclusively or C
exclusively and hate the other language (probably more C writers that hate C++
than C++ writers that hate C).

Some people write very C-accented C++, with mallocs and frees instead of news
and deletes and so forth (these are usually people who prefer C over C++ but
are writing C++ for whatever reason). I guess those people could be said to be
writing "C/C++". But in general I think people overestimate how close the two
language communities are. What I have seen is that people like one language
and deride the other.

~~~
generic_user
There are some people that probably get to worked up about it especially on
the internet as you said. But in a professional environment where you have
deadlines and a budget you don't have the luxury to be a language purist. You
have to use libraries and choose from whats available and whats the best
choice often that means mixing C and C++. I'm not saying that people
necessarily like to code in C if they prefer C++ or the other way around but
they will often have to. And so have some competency weather they like it or
not.

------
OliverJones
The Evans and Sutherland graphics rendering pipeline has been doing this for
almost two generations. Dr. Sutherland's clipping divider depends on it.
[https://www.google.com/patents/US3639736](https://www.google.com/patents/US3639736)

------
spuz
Numberphile did a good simple explanation of quaternions:
[https://www.youtube.com/watch?v=3BR8tK-
LuB0](https://www.youtube.com/watch?v=3BR8tK-LuB0)

------
ipunchghosts
You will eventually regret any use of Euler angles. - John Carmack

~~~
Coincoin
I would agree if it said "most" instead of "any". Euler angles are useful.
Just be very careful with them. Convert to quaternion as soon as possible and
convert back to euler as late as possible when needed.

However, you will never entirely avoid them because they are just too
practical. Under careful constraints, they make code interfaces simpler.

This is especially important if you are to expose that code to a
multidisciplinary team. There is no way you're going to teach an artist how
quaternions work just so they can rotate their stuff around the up axis, when
simple yaw-pitch angles cover 99% of their use cases.

------
na85
So much js on that page that it took almost a minute to finish loading, and
then my phone's browser froze.

~~~
wmil
He's using MathJax to display equations. There are a lot of equations.

[https://www.mathjax.org/](https://www.mathjax.org/)

