miguelcorderopamphile opened a new pull request, #11315:
URL: https://github.com/apache/arrow-rs/pull/11315

   # Which issue does this PR close?
   
   - Closes #11314.
   
   # Rationale for this change
   
   `i256_to_f64` normalizes the input, keeps the top 64 bits and discards the 
lower 192, so the final `i64 as f64` rounds a value truncated at 64 bits. When 
the discarded bits put the exact value just past a binary64 midpoint, the 
result can round to the wrong neighbor: `(1_i128 << 63) + 1024 + 1` returns 
`0x43e0000000000000` instead of `0x43e0000000000001`.
   
   # What changes are included in this PR?
   
   Set a sticky bit on the retained value when any discarded bit is non-zero, 
so midpoint ties round to nearest (ties to even only apply when the exact value 
is the midpoint). No API changes. A naive `top + 1` variant was also checked 
and is incorrect, since it can move a value that sits just below a midpoint up 
to the midpoint; setting the low bit preserves the side of the midpoint.
   
   # Are these changes tested?
   
   - The reported value plus midpoint neighborhoods for every binary64 exponent 
in `i256` range, both signs, checked against `to_string().parse::<f64>()`.
   - `MIN`, `MAX`, `-1`, `0`, `1`, and 1000 deterministic pseudo-random 
full-range values against the same oracle.
   - `cargo test -p arrow-buffer` (358 passed) and `cargo test -p arrow-cast 
--lib test_cast_decimal256` (12 passed); `cargo fmt --check` and `cargo clippy 
-p arrow-buffer --all-targets -- -D warnings` clean.
   
   # Are there any user-facing changes?
   
   No API changes. `i256::to_f64` now returns the correctly rounded `f64`, 
which also fixes `Decimal256 -> Float64` casts that use it.
   
   # AI usage disclosure
   
   Per CONTRIBUTING: the sticky-bit approach was suggested in the issue. I 
reproduced the failure, validated the approach at scale against correctly 
rounded conversions (midpoint sweeps and randomized comparisons, including 
ruling out the `+1` variant), and wrote the tests. AI assistance was used for 
analysis and drafting; I have reviewed and verified every change and own the 
final implementation.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to