ocaml icon indicating copy to clipboard operation
ocaml copied to clipboard

float_of_string misrounds subnormal hex doubles

Open kayceesrk opened this issue 3 weeks ago • 1 comments

float_of_string "0x50000000000001p-1127" returns the double with bits 2, where the exact result rounds to 3.

$ cat test.ml
(* test.ml *)
let bits x = Int64.to_string (Int64.bits_of_float x)
let () =
  Printf.printf "%s vs %s\n"
    (bits (float_of_string "0x50000000000001p-1127"))
    (bits (Float.ldexp 3.0 (-1074)))
$ ocamlopt test.ml -o test && ./test
2 vs 3

0x50000000000001p-1127 is 2.5 ulps plus 2^-1127, with ulp = 2^-1074, so it should round up to 3.

caml_float_of_hex (runtime/floats.c:364) collects at most 60 mantissa bits with round-to-odd and then converts in two steps, f = (double) (int64_t) m; and if (exp != 0) f = ldexp(f, exp);. When the result is subnormal the first step rounds to 53 bits and can leave exactly a midpoint of the coarser subnormal grid, and ldexp then breaks the tie by evenness rather than by the true value.

Across 14149 subnormal results from random 0x...p-e strings, 133 are one ulp off and none of the 1303 normal results tested is wrong. I see this on 5.5.0. The same two-step conversion is on trunk.

Discovered with DeepSeek v4.1 flash.

kayceesrk avatar Nov 12 '26 06:11 kayceesrk

I have a fix: for a subnormal result, caml_float_of_hex now rounds the mantissa once, directly to the subnormal precision, and then scales it exactly, instead of converting to double and then calling ldexp. Compared with exact rational rounding on 300,000 random hex strings, trunk gives 230 wrong results and the fix gives none; the full testsuite passes. I’ll open a PR shortly.

Shakhtar-Sankur avatar Nov 18 '26 15:11 Shakhtar-Sankur