Commit a624878b
a624878b9aabMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 5 files · +2 added · ~3 modified
Description
codegen: compute Float#round/ceil/floor/truncate exactly for a non-literal ndigits
With a literal-integer ndigits these methods already match CRuby's value-
based return class (Integer for ndigits <= 0, Float for ndigits > 0). With
a NON-literal ndigits the C backend dropped the argument entirely and
emitted (mrb_int)round(x), which both forced Integer and discarded the
precision: 1.234.round(n) with n==2 returned 1 instead of 1.23, and
1234.5.round(n) with n==-1 returned 1235 instead of 1230. Those are
wrong values, not just a #class difference.
Restore the documented behavior: a non-literal ndigits is typed Float and
lowered to the runtime form round(x * 10**n) / 10**n, which is exact for
any n. The result is numerically equal to CRuby's; only #class (and the
default string form) still differs when n turns out <= 0, the residual
divergence already described in docs/FLOAT-ROUNDING.md. Code needing an
Integer converts with .to_i.
Also refresh that doc's stale implementation pointers (the legacy spinel_analyze.rb / spinel_codegen.rb are now analyze_infer.c / codegen_call.c).
Co-Authored-By: Claude Opus 4.8 [email protected]
Details
- Commit
- a624878b9aab
- Parent
- fa7999fed514
docs/FLOAT-ROUNDING.mdmodifiedView file
So `x.round(n)` where `n` is a variable holding a non-positive valuereturns a Float (`10.0`) where CRuby returns an Integer (`10`). Thevalues are numerically equal; only `#class` and the default string form(`"10.0"` vs `"10"`) differ. Code that needs an Integer can convert**value is still computed exactly** (`1.234.round(n)` with `n == 2` is`1.23`, `1234.5.round(n)` with `n == -1` is `1230.0`); the values arenumerically equal to CRuby's and only `#class` and the default stringform (`"10.0"` vs `"10"`) differ. Code that needs an Integer can convertexplicitly: `x.round(n).to_i`.The implementation lives in `infer_method_name_type` (spinel_analyze.rb)and `compile_float_round_expr` (spinel_codegen.rb); both classify aliteral-integer `ndigits` by sign and fall back to Float otherwise.The implementation lives in `infer_call` (`src/analyze_infer.c`) and`emit_scalar_call` (`src/codegen_call.c`); both classify a literal-integer`ndigits` by sign and fall back to an exact Float computation otherwise.src/analyze_infer.cmodifiedView file
Loading diff…
src/codegen_call.cmodifiedView file
Loading diff…
test/float_round_nonliteral.rbaddedView file
Loading diff…
test/float_round_nonliteral.rb.expectedaddedView file
Loading diff…