Version française
Home     About     Download     Resources     Contact us    
Browse thread
[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: -- (:)
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);;

let add_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 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? 

Thanks in advance.

Rolf Wester

 

-------------------------------------
Rolf Wester
wester@ilt.fhg.de
-------------------
To unsubscribe, mail caml-list-request@inria.fr.  Archives: http://caml.inria.fr