factor/basis/math/quaternions/quaternions.factor

67 lines
1.3 KiB
Factor
Raw Normal View History

2007-09-20 18:09:08 -04:00
! Copyright (C) 2005, 2007 Slava Pestov.
! See http://factorcode.org/license.txt for BSD license.
2008-11-17 21:12:10 -05:00
USING: arrays kernel math math.functions math.vectors sequences ;
IN: math.quaternions
2007-09-20 18:09:08 -04:00
2008-11-17 21:12:10 -05:00
! Everybody's favorite non-commutative skew field, the quaternions!
2007-09-20 18:09:08 -04:00
2008-11-17 21:12:10 -05:00
! Quaternions are represented as pairs of complex numbers, using the
! identity: (a+bi)+(c+di)j = a+bi+cj+dk.
2007-09-20 18:09:08 -04:00
<PRIVATE
: ** ( x y -- z ) conjugate * ; inline
2007-09-20 18:09:08 -04:00
2008-03-29 21:36:58 -04:00
: 2q ( u v -- u' u'' v' v'' ) [ first2 ] bi@ ; inline
2007-09-20 18:09:08 -04:00
: q*a ( u v -- a ) 2q swapd ** [ * ] dip - ; inline
2007-09-20 18:09:08 -04:00
: q*b ( u v -- b ) 2q [ ** swap ] dip * + ; inline
2007-09-20 18:09:08 -04:00
PRIVATE>
: q* ( u v -- u*v )
2008-07-04 12:19:42 -04:00
[ q*a ] [ q*b ] 2bi 2array ;
2007-09-20 18:09:08 -04:00
: qconjugate ( u -- u' )
2008-10-03 03:19:03 -04:00
first2 [ conjugate ] [ neg ] bi* 2array ;
2007-09-20 18:09:08 -04:00
: qrecip ( u -- 1/u )
qconjugate dup norm-sq v/n ;
: q/ ( u v -- u/v )
qrecip q* ;
: q*n ( q n -- q )
conjugate v*n ;
: c>q ( c -- q )
0 2array ;
: v>q ( v -- q )
first3 rect> [ 0 swap rect> ] dip 2array ;
2007-09-20 18:09:08 -04:00
: q>v ( q -- v )
first2 [ imaginary-part ] dip >rect 3array ;
2007-09-20 18:09:08 -04:00
! Zero
CONSTANT: q0 { 0 0 }
2007-09-20 18:09:08 -04:00
! Units
CONSTANT: q1 { 1 0 }
CONSTANT: qi { C{ 0 1 } 0 }
CONSTANT: qj { 0 1 }
CONSTANT: qk { 0 C{ 0 1 } }
2007-09-20 18:09:08 -04:00
2008-11-17 21:12:10 -05:00
! Euler angles
<PRIVATE
2007-09-20 18:09:08 -04:00
: (euler) ( theta unit -- q )
2008-11-17 21:12:10 -05:00
[ -0.5 * [ cos c>q ] [ sin ] bi ] dip n*v v- ;
PRIVATE>
2007-09-20 18:09:08 -04:00
: euler ( phi theta psi -- q )
2008-07-04 12:22:59 -04:00
[ qi (euler) ] [ qj (euler) ] [ qk (euler) ] tri* q* q* ;