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: Xavier Leroy <Xavier.Leroy@i...>
Subject: Re: [Caml-list] Complex numbers in OCaml
> I need complex numbers. I tried it this way:
> type number  = Real of float | Complex of (float*float);;
> [...]
> This works but is quite cumbersome to use.
> Is there any other way to do it

Unless you have strong reasons for doing so, I'd advise against the
mixed-mode arithmetic (i.e. having a special case for Real): it makes
operations slower and more complex.

In terms of performance, the best representation is a record type:

        type complex = { re: float; im: float }

since the compiler will then unbox the two floats.  This would not be
the case for a pair of floats:

        type complex = float * float

The concrete syntax is a bit heavy, e.g. {re = 1.0; im = 0.0}, but at
least highly non-ambiguous :-)  If you're desperate for a more compact
notation, Camlp4 could help.

One last performance hint: write b *. b rather than b ** 2.0,
it's much, much faster.

> and how can arrays of complex numbers be implemented efficiently in OCaml? 

Just regular arrays of complex numbers, e.g. the type "complex array",
should be reasonably efficient, although you pay one extra indirection
compared with the equivalent C or Fortran array.

As Markus mentioned, I'm considering extending the Bigarray module to
handle complex numbers as well.  This would help interfacing with
Fortran, and provide essentially the same data representation than in
C and Fortran.

- Xavier Leroy
-------------------
To unsubscribe, mail caml-list-request@inria.fr.  Archives: http://caml.inria.fr