English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    
Browse thread
[Caml-list] string_of_float less accurate than sprintf "%f" ?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: David McClain <dmcclain1@m...>
Subject: Re: [Caml-list] string_of_float less accurate than sprintf "%f" ?
Xavier Leroy writes:

> There might be a more philosophical issue behind this.  For a
> numerical analyst, or physicist, or experimental scientist in general,
....

I am such a scientist, and in fact the numeric representation I seek
generally depends heavily on the experimental precision available. So I
ended up writing a flexible printf routine in OCaml to support printing only
as many decimal places as afforded by the standard deviation of my
measurements. It was easy to do, but it did require the use of magic...

Here is the general formatting routine...

let fmt_val_sigma title value sigma =
  let rec iter sf x =
    if x >= 1.0 then
      if sf > 4 then
 printf "%g (%g)\n" value sigma
      else
 printf (U.as_format
    (sprintf "%%%d.%df (%%%d.%df)\n"
       (sf + 3) sf (sf + 2) sf))
   value sigma
    else
      iter (sf + 1) (x *. 10.0)
  in
    printf "%20s = " title;
    if sigma = 0.0 then printf "%g\n" value
    else
      iter 0 sigma

Here is a sample of its use...

     fmt_val_sigma "psf_scale"  sys.parms.psf_scale sigma_scale;

where the value of interest is psf_scale, and its standard deviation is
sigma_scale. The rouitne above examines the standard deviation and
determines the appropriate print format, typically in the form  "title 1.03
(5)"  where the value is 1.03 and the standard deviation is 0.05, or (5) in
the last place...

And here is the "magic" in module Utility.ml and Utility.mli (the
U.as_format in the above code)

Utility.mli:
(* convert a dynamic string to a printf format *)
val as_format : string -> ('a, out_channel, unit) format

Utility.ml:
(* as_format allows to build a string that can later be used *)
(* as a printf format string *)
let as_format (str : string) =
  (Obj.magic str : ('a,out_channel,unit) format)

Cheers,

- David McClain, Sr. Scientist, Raytheon Missile Systems Co., Tucson, AZ

-------------------
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