]> gitweb.factorcode.org Git - factor.git/blob - basis/math/quaternions/quaternions.factor
Merge branch 'for-slava' of git://git.rfc1149.net/factor
[factor.git] / basis / math / quaternions / quaternions.factor
1 ! Copyright (C) 2005, 2007 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays kernel math math.functions math.vectors sequences ;
4 IN: math.quaternions
5
6 ! Everybody's favorite non-commutative skew field, the quaternions!
7
8 ! Quaternions are represented as pairs of complex numbers, using the
9 ! identity: (a+bi)+(c+di)j = a+bi+cj+dk.
10
11 <PRIVATE
12
13 : ** ( x y -- z ) conjugate * ; inline
14
15 : 2q ( u v -- u' u'' v' v'' ) [ first2 ] bi@ ; inline
16
17 : q*a ( u v -- a ) 2q swapd ** [ * ] dip - ; inline
18
19 : q*b ( u v -- b ) 2q [ ** swap ] dip * + ; inline
20
21 PRIVATE>
22
23 : q* ( u v -- u*v )
24     [ q*a ] [ q*b ] 2bi 2array ;
25
26 : qconjugate ( u -- u' )
27     first2 [ conjugate ] [ neg  ] bi* 2array ;
28
29 : qrecip ( u -- 1/u )
30     qconjugate dup norm-sq v/n ;
31
32 : q/ ( u v -- u/v )
33     qrecip q* ;
34
35 : q*n ( q n -- q )
36     conjugate v*n ;
37
38 : c>q ( c -- q )
39     0 2array ;
40
41 : v>q ( v -- q )
42     first3 rect> [ 0 swap rect> ] dip 2array ;
43
44 : q>v ( q -- v )
45     first2 [ imaginary-part ] dip >rect 3array ;
46
47 ! Zero
48 CONSTANT: q0 { 0 0 }
49
50 ! Units
51 CONSTANT: q1 { 1 0 }
52 CONSTANT: qi { C{ 0 1 } 0 }
53 CONSTANT: qj { 0 1 }
54 CONSTANT: qk { 0 C{ 0 1 } }
55
56 ! Euler angles
57
58 <PRIVATE
59
60 : (euler) ( theta unit -- q )
61     [ -0.5 * [ cos c>q ] [ sin ] bi ] dip n*v v- ;
62
63 PRIVATE>
64
65 : euler ( phi theta psi -- q )
66   [ qi (euler) ] [ qj (euler) ] [ qk (euler) ] tri* q* q* ;