1 ! Copyright (C) 2005 Slava Pestov.
2 ! See http://factor.sf.net/license.txt for BSD license.
4 ! Everybody's favorite non-commutative skew field, the
7 ! Quaternions are represented as pairs of complex numbers,
8 ! using the identity: (a+bi)+(c+di)j = a+bi+cj+dk.
9 USING: arrays kernel math sequences math-contrib ;
10 IN: quaternions-internals
12 : 2q [ first2 ] 2apply ; inline
14 : q*a 2q swapd ** >r * r> - ; inline
16 : q*b 2q >r ** swap r> * + ; inline
21 #! Multiply quaternions.
22 [ q*a ] 2keep q*b 2array ;
24 : qconjugate ( u -- u' )
25 #! Quaternion conjugate.
26 first2 neg >r conjugate r> 2array ;
29 #! Quaternion inverse.
30 qconjugate dup norm-sq v/n ;
33 #! Divide quaternions.
37 #! Note: you will get the wrong result if you try to
38 #! multiply a quaternion by a complex number on the right
39 #! using v*n. Use this word instead. Note that v*n with a
40 #! quaternion and a real is okay.
44 #! Turn a complex number into a quaternion.
48 #! Turn a 3-vector into a quaternion with real part 0.
49 first3 rect> >r 0 swap rect> r> 2array ;
52 #! Get the vector part of a quaternion, discarding the real
54 first2 >r imaginary r> >rect 3array ;
56 : cross ( u v -- u*v )
57 #! Cross product of two 3-vectors can be computed using
58 #! quaternion multiplication.
59 [ v>q ] 2apply q* q>v ;
71 ! http://www.mathworks.com/access/helpdesk/help/toolbox/aeroblks/euleranglestoquaternions.html
73 : (euler) ( theta unit -- q )
74 >r -0.5 * dup cos c>q swap sin r> n*v v- ;
76 : euler ( phi theta psi -- q )
77 qk (euler) >r qj (euler) >r qi (euler) r> q* r> q* ;