Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduced precision when converting floats to strings #4345

Closed
vicuna opened this issue Jul 17, 2007 · 0 comments
Closed

Reduced precision when converting floats to strings #4345

vicuna opened this issue Jul 17, 2007 · 0 comments

Comments

@vicuna
Copy link

vicuna commented Jul 17, 2007

Original bug ID: 4345
Reporter: brunodefraine
Assigned to: @xclerc
Status: closed (set by @xavierleroy on 2013-08-31T10:44:32Z)
Resolution: fixed
Priority: normal
Severity: minor
Version: 3.10.0
Fixed in version: 3.12.1+dev
Category: -for Camlp4 use https://github.com/ocaml/camlp4/issues
Related to: #3352 #4767
Monitored by: @Chris00

Bug description

First, consider the top-level printing of values:

$ ocaml

let pi = 3.14159265358979312 ;;

val pi : float = 3.14159265358979312

float_of_string "3.14159265358979312" = pi ;;

  • : bool = true

While:

$ ocaml camlp4rf.cma

value pi = 3.14159265358979312 ;

value pi : float = 3.14159265359

float_of_string "3.14159265359" = pi ;

  • : bool = False

Similarly, consider `flo antiquotations:

$ ocaml camlp4rf.cma

open Camlp4.PreCast;

value _loc = Loc.ghost;

value pi = 3.14159265358979312;

<:expr< $`flo:pi$ >> ;

  • : Camlp4.PreCast.Ast.expr =
    Camlp4.PreCast.Ast.ExFlo "3.14159265359"

While it might not be possible to produce string versions whose float_of_string value always exactly equals the original float value, the precision of the currently produced versions is far below the precision of Ocaml's float type.

Additional information

This is probably related to the usage of string_of_float to produce the string versions. Consider the following alternative, located inside typing/oprint.ml, and probably used by OCaml's standard toplevel:

let float_repres f =
match classify_float f with
FP_nan -> "nan"
| FP_infinite ->
if f < 0.0 then "neg_infinity" else "infinity"
| _ ->
let s1 = Printf.sprintf "%.12g" f in
if f = float_of_string s1 then valid_float_lexeme s1 else
let s2 = Printf.sprintf "%.15g" f in
if f = float_of_string s2 then valid_float_lexeme s2 else
Printf.sprintf "%.18g" f

@vicuna vicuna closed this as completed Aug 31, 2013
@vicuna vicuna added the camlp4 label Mar 14, 2019
@vicuna vicuna added the bug label Mar 19, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant