Quaternion type: Difference between revisions

Content deleted Content added
mNo edit summary
added ocaml
Line 584: Line 584:
q2 mul q1
q2 mul q1
_56 18 20 28</lang>
_56 18 20 28</lang>

=={{header|OCaml}}==

<lang ocaml>type quaternion = float * float * float * float

let q a b c d = (a, b, c, d)
let to_real (r, _, _, _) = r
let imag (_, i, j, k) = (i, j, k)
let scalar_of_quaternion s = (s, 0.0, 0.0, 0.0)
let to_list (a, b, c, d) = [a; b; c; d]
let of_list = function [a; b; c; d] -> (a, b, c, d)
| _ -> invalid_arg "of_list"
let ( + ) = ( +. )
let ( - ) = ( -. )
let ( * ) = ( *. )
let ( / ) = ( /. )

let addr (a, b, c, d) r = (a+r, b, c, d)
let mulr (a, b, c, d) r = (a*r, b*r, c*r, d*r)

let add (a, b, c, d) (p, q, r, s) = (a+p, b+q, c+r, d+s)
let sub (a, b, c, d) (p, q, r, s) = (a-p, b-q, c-r, d-s)
let mul (a, b, c, d) (p, q, r, s) =
( a*p - b*q - c*r - d*s,
a*q + b*p + c*s - d*r,
a*r - b*s + c*p + d*q,
a*s + b*r - c*q + d*p )
let norm2 (a, b, c, d) =
( a * a +
b * b +
c * c +
d * d )

let norm q = sqrt(norm2 q)
let conj (a, b, c, d) = (a, -. b, -. c, -. d)
let neg (a, b, c, d) = (-. a, -. b, -. c, -. d)

let unit ((a, b, c, d) as q) =
let n = norm q in
(a/n, b/n, c/n, d/n)

let reciprocal ((a, b, c, d) as q) =
let n2 = norm2 q in
(a/n2, b/n2, c/n2, d/n2)</lang>


<lang ocaml>type quaternion = float * float * float * float

val q : float -> float -> float -> float -> quaternion
val to_real : quaternion -> float
val imag : quaternion -> float * float * float
val scalar_of_quaternion : float -> quaternion
val to_list : quaternion -> float list
val of_list : float list -> quaternion
val addr : quaternion -> float -> quaternion
val mulr : quaternion -> float -> quaternion
val add : quaternion -> quaternion -> quaternion
val sub : quaternion -> quaternion -> quaternion
val mul : quaternion -> quaternion -> quaternion
val norm : quaternion -> float
val conj : quaternion -> quaternion
val neg : quaternion -> quaternion
val unit : quaternion -> quaternion
val reciprocal : quaternion -> quaternion</lang>

<pre>
$ ocamlc -c q.mli
$ ocamlc -c q.ml
$ ocaml q.cmo
Objective Caml version 3.11.2

# open Q ;;
# let q1 = q 2.0 3.0 4.0 5.0
and q2 = q 3.0 4.0 5.0 6.0 ;;
val q1 : Q.quaternion = (2., 3., 4., 5.)
val q2 : Q.quaternion = (3., 4., 5., 6.)
# (mul q1 q2) <> (mul q2 q1) ;;
- : bool = true
</pre>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Structure Quaternion
<lang PureBasic>Structure Quaternion