Browse thread
Strange behaviour of string_of_float
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Brian Hurt <bhurt@s...> |
| Subject: | Re: [Caml-list] Strange behaviour of string_of_float |
On Sun, 22 Jun 2008, Paolo Donadeo wrote:
> I know what a float number is from my numerical analysis course :-).
>
> In any case, what is the suggested way to serialize/deserialize a
> float number in OCaml? The Sexplib, for example, suffers the same
> problem of the string_of_float function:.
>
> My intent is to extract an ASCII representation of an OCaml float
> value so that it can be used to recreate *exactly* the same value, at
> least on the same architecture.
>
Code something like this should work:
let encode_float x =
match (classify_float x) with
| FP_zero -> if (x = -0.0) then "-0.0" else "0.0"
| FP_infinite -> if (x = neg_infinity) then "-INF" else "INF"
| FP_nan -> "NaN"
| _ ->
let s = x < 0.0 in
let x = abs_float x in
let frac, exp = frexp x in
let frac = frac *. 268435456.0 in (* 2^28 *)
let i1 = int_of_float frac in
let i2 = int_of_float ((frac -. (floor frac)) *. 268435456.0) in
let exp = exp - 56 in
let s2 = exp < 0 in
let exp = if exp < 0 then -exp else exp in
Printf.sprintf "%c%07X%07XX%c%X" (if s then '-' else '+') i1 i2
(if s2 then '-' else '+') exp
;;
I'll leave the decode to you- it should be obvious, once you discover the
ldexp function.
Brian