Version française
Home     About     Download     Resources     Contact us    
Browse thread
Re: [Caml-list] Runtime overflow and what to do
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Pierre Weis <pierre.weis@i...>
Subject: Re: [Caml-list] Runtime overflow and what to do
Hi again,

> On Sun, Oct 13, 2002 at 12:29:58PM +0200, Pierre Weis wrote:
> 
> > let ( * ) n m =
> >  if num_bits_int n + num_bits_int m < length_of_int
> >  then n * m else raise (Overflow ("*", string_of_int n, string_of_int m))
> 
> Does it work with negative numbers? And with multiplication between a
> positive and a negative number?

Yes it does.

> > Just to let people play with the writting of the module :),
> > num_bits_int is left as an exercise to the interested readers (3 lines
> > of Caml code using trivial bit shuffling).
> 
> I am interested in knowing it, because I already searched that.
> Without a loop or a predefined array of powers of two, I don't
> know how to do that.

Nor did I. I think there exists processors that do have an instruction
to implement this function but this is not the general case: you need
to write a loop or use a predefined array of powers of two or write a
dichotomic algorithm or whatever...

For instance:

let num_bits_int n =
  let rec num_bits n = if n = 0 then 0 else succ (num_bits (n lsr 1)) in
  num_bits (abs n);;

(No dichotomy, here. Experiments with a dichotomic algorithm is also
interesting, but deciding which is faster is difficult since
benchmarking is almost impossible: the results are too much dependant
of the value of integers manipulated in the program.)

Pierre Weis

INRIA, Projet Cristal, Pierre.Weis@inria.fr, http://pauillac.inria.fr/~weis/


-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners