0178: Shortest round-trip f64 text, identical on both backends
Status: Proposed (pending maintainer)
Context
printf("%g") loses precision and differs between C
libraries; Rust's Display never uses an exponent, so
1e300 prints 301 digits. Output must be deterministic
and byte-identical between harness interp and
compiled C.
Decision
Printing, println and interpolation use one
format:
- Digits are the shortest decimal string that parses back to the same value; among equally short strings, the one closest to the exact value (Steele–White/Dragon4 free-format, as Ryu and Rust produce).
- With scientific exponent
x(valued.ddd × 10^x), use positional notation when-7 < x < 21, otherwised.ddde<x>. Always keep a fraction:1.0,100.0,0.30000000000000004,1.0e21,1.5e-7,5.0e-324. Every finite result is a valid Harness literal. -0.0prints-0.0; infinities printinfand-inf; every NaN printsnan(the sign and payload of NaN are not portable).
The interpreter takes Rust's shortest digits
({:e}); the C runtime has its own exact bignum
Dragon4 in runtime/hrt_f64.h and does not call
printf. A seeded runtime test compares the two on random bit
patterns.
s.parse_f64() -> option<f64> accepts
exactly
[+-]? digits ('.' digits)? ([eE] [+-]? digits)? and
[+-]?inf, nan (ASCII, no spaces), so
every printed value parses back. The result is correctly rounded;
overflow gives ±inf, not none. The interpreter uses Rust's parser;
C validates the grammar and calls strtod (correctly
rounded on glibc, musl and macOS; the runtime never changes the
"C" locale).
Consequences
Golden outputs for floats are portable. Printing costs a bignum loop in C (≤ 1,280-bit integers); it is not on a hot path today and can move to Ryu behind the same output if a benchmark asks for it.
Alternatives
%.17g: round-trips but prints0.1as0.10000000000000001, and its exponent spelling varies by C library.- Rust
Displayeverywhere: no exponent form; huge outputs. - Ryu in C: faster but adds ~10 KB of tables to every program that prints floats.