Version française
Home     About     Download     Resources     Contact us    
Browse thread
Strange behaviour of string_of_float
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jon Harrop <jon@f...>
Subject: Re: [Caml-list] Strange behaviour of string_of_float
On Sunday 22 June 2008 20:58:31 Richard Jones wrote:
> On Sun, Jun 22, 2008 at 06:56:22PM +0200, Paolo Donadeo wrote:
> > string_of_float is not the inverse of float_of_string, at least in
> > this example.
>
> Yes, you wouldn't expect it to be, because the string is an
> approximate base 10 representation of the float...

That is not true. All finite floats have exact finite decimal representations. 
So it is perfectly reasonable to expect the conversions to recover the 
original number exactly.

As Paolo has shown, OCaml's current string_of_float function is approximate. 
The accuracy of this routine is unspecified but a quick test indicates that 
it is simply printing too few digits to be exact:

# string_of_float pi;;
- : string = "3.14159265359"

Fortunately, you can ask sprintf to generate a sufficiently accurate result:

# open Printf;;
# sprintf "%0.17g" pi;;
- : string = "3.1415926535897931"

The float_of_string function does then recover the number exactly in this 
case:

# float_of_string "3.1415926535897931" -. pi;;
- : float = 0.

Also, you should keep in mind in this context that calculations may be done 
with 80-bit float arithmetic in registers or truncated to 64-bits when stored 
to memory. Moreover, OCaml's bytecode and native code targets can behave 
differently in this context. I do not believe that is a problem with Paolo's 
code here though.

-- 
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
http://www.ffconsultancy.com/products/?e