This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

[Caml-list] Complex numbers in OCaml
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2001-03-27 (16:22) From: wester@i... Subject: [Caml-list] Complex numbers in OCaml
```Hi,

I need complex numbers. I tried it this way:

type number  = Real of float | Complex of (float*float);;

match (a,b) with
(Real a, Real b)          -> Real (a +. b)
| (Real a, Complex (bx,by)) -> Complex (a +. bx, by)
| (Complex (ax,ay), Real b) -> Complex (ax +. b, ay)
| (Complex (ax,ay), Complex (bx,by)) -> Complex (ax +. bx, ay +. by);;
let sub_num a b =
match (a,b) with
(Real a, Real b)          -> Real (a -. b)
| (Real a, Complex (bx,by)) -> Complex (a -. bx, by)
| (Complex (ax,ay), Real b) -> Complex (ax -. b, ay)
| (Complex (ax,ay), Complex (bx,by)) -> Complex (ax -. bx, ay -. by);;
let mul_num a b =
match (a,b) with
(Real a, Real b)          -> Real (a *. b)
| (Real a, Complex (bx,by)) -> Complex (a *. bx, a *. by)
| (Complex (ax,ay), Real b) -> Complex (ax *. b, ay)
| (Complex (ax,ay), Complex (bx,by)) -> Complex (ax *. bx -. ay *. by, ax *. by +. ay *. bx);;
let div_num a b =
match (a,b) with
(Real a, Real b)          -> Real (a /. b)
| (Real a, Complex (bx,by)) -> Complex (a *. bx /. (bx**2.0 +. by**2.0),
-. a *. by /. (bx**2.0 +. by**2.0))
| (Complex (ax,ay), Real b) -> Complex (ax /. b, ay /. b)
| (Complex (ax,ay), Complex (bx,by)) -> let n = bx**2.0 +. by**2.0 in
Complex ((ax *. bx +. ay *. by)/.n,
(ay *. bx -. ax *. by)/.n);;
let conj a =
match a with
Real a -> Real a;
| Complex (ax,ay) -> Complex (ax, -. ay);;
let real a =
match a with
Real a -> a
|Complex (ax, ay) -> ax;;
let imag a =
match a with
Real a -> 0.0
|Complex (ax, ay) -> ay;;

div_num (Complex (2.0,3.0)) (Complex (3.0,2.0));;

This works but is quite cumbersome to use. Is there any other way to do it and how can
arrays of complex numbers be implemented efficiently in OCaml?