Calculate Quaternion Inverse

user346443 picture user346443 · Jul 14, 2011 · Viewed 12.3k times · Source

Hi i'm trying to figure out how to calculate the inverse of a quaternion. A code example would be awesome.

Cheers

Answer

Mihai Maruseac picture Mihai Maruseac · Jul 14, 2011

See Wikipedia article for the entire Quaternion math.

Don't know what language you want to use but I'll try to give some hints in Haskell.

data Quaternion = Q Double Double Double Double deriving (Show, Eq)

First, you need to implement multiplication and addition of quaternions.

instance Num Quaternion where
 (+) = q_plus
 (*) = q_mult
 --....

q_plus (Q a b c d) (Q a' b' c' d') = Q (a + a') (b + b') (c + c') (d + d')
q_mult (Q a b c d) (Q a' b' c' d') = Q a'' b'' c'' d''
  where
    a'' = a * a' - b * b' - c * c' - d * d'
    b'' = a * b' + b * a' + c * d' - d * c'
    c'' = a * c' - b * d' + c * a' + d * b'
    d'' = a * d' + b * c' - c * b' + d * a'

Multiplication with scalar should be done via a conversion:

scalar_to_q a = Q a 0 0 0

Define

i = Q 0 1 0 0
j = Q 0 0 1 0
k = Q 0 0 0 1

Then implement the conjugate and modulus:

q_conjugate q = (scalar_to_q (negate .5)) * (q + i * q * i + j * q * j + k * q * k)
q_modulus q = sqrt $ q * (q_conjugate q)

Now, the inverse:

q_inverse q = (q_conjugate q) * (scalar_to_q (m * m))
  where
    m = q_modulus q

Hope it's useful.

PS: the instance definition above will simplify things a little if completed successfully. I let you fill in the gaps.