Advertisement
VladNitu

6w3

Feb 29th, 2024
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. import Prelude
  2.  
  3. data Quaternion = Quat { a :: Double,
  4. b :: Double,
  5. c :: Double,
  6. d :: Double }
  7. deriving Eq
  8.  
  9. -- Take the real part of a quaternion (used for testing)
  10. -- realPart (a + b*i + c*j + d*k) == a
  11. realPart :: Quaternion -> Double
  12. realPart q = (a q)
  13.  
  14. i, j, k, zeroQuat :: Quaternion
  15. i = Quat 0 1 0 0
  16. j = Quat 0 0 1 0
  17. k = Quat 0 0 0 1
  18. zeroQuat = Quat 0 0 0 0
  19.  
  20. fromDouble :: Double -> Quaternion
  21. fromDouble x = Quat x 0 0 0
  22.  
  23. instance Show Quaternion where
  24. show (Quat a b c d) = show a ++ " + " ++ show b ++ "i + " ++ show c ++ "j + " ++ show d ++ "k"
  25.  
  26.  
  27. instance Num Quaternion where
  28. q1 + q2 = Quat (a q1 + a q2) (b q1 + b q2) (c q1 + c q2) (d q1 + d q2)
  29. q1 * q2 = Quat a_term b_term c_term d_term
  30. where
  31. a_term = a q1 * a q2 - b q1 * b q2 - c q1 * c q2 - d q1 * d q2
  32. b_term = a q1 * b q2 + b q1 * a q2 + c q1 * d q2 - d q1 * c q2
  33. c_term = a q1 * c q2 - b q1 * d q2 + c q1 * a q2 + d q1 * b q2
  34. d_term = a q1 * d q2 + b q1 * c q2 - c q1 * b q2 + d q1 * a q2
  35.  
  36. abs q = fromDouble (sqrt (sum_prod))
  37. where
  38. sum_prod = a q * a q + b q * b q + c q * c q + d q * d q
  39.  
  40. -- Divide each Double component by the (abs x)
  41. signum q =
  42. if q /= zeroQuat then
  43. Quat (a q / absVal) (b q / absVal) (c q / absVal) (d q / absVal)
  44. else
  45. zeroQuat
  46. where
  47. absVal = realPart (abs q)
  48.  
  49. negate q = Quat (- a q) (- b q) (- c q) (-d q)
  50. fromInteger n = Quat (fromIntegral n) 0 0 0
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement