Repository navigation
Conversation
…semantics The documentation for `<float as Rem>::rem` previously presented the formula `x - (x / y).trunc() * y` as if it were a Rust expression, but this operation is actually computed using infinite precision (exact) arithmetic, then rounded to the result type (equivalent to C's `fmod`). Evaluating the expression literally in Rust can produce different results due to intermediate rounding at each floating-point operation. This clarifies the docs to explicitly state the formula is mathematical and notes the discrepancy with the literal Rust expression. The example is also simplified to avoid suggesting the two are equivalent. Fixes rust-lang#133758 Co-Authored-By: Claude (claude-opus-4-6) <noreply@anthropic.com>
|
r? @joboet rustbot has assigned @joboet. Use Why was this reviewer chosen?The reviewer was selected based on:
|
|
|
r? @traviscross |
| /// let x: f32 = 50.50; | ||
| /// let y: f32 = 8.125; | ||
| /// let remainder = x - (x / y).trunc() * y; | ||
| /// | ||
| /// // The answer to both operations is 1.75 | ||
| /// assert_eq!(x % y, remainder); | ||
| /// assert_eq!(x % y, 1.75); |
There was a problem hiding this comment.
Could you add assert!((x % 0.0).is_nan()) to demo the zero case? Infinity would be good as well.
| /// The remainder has the same sign as the dividend and is computed | ||
| /// as the exact value `x - trunc(x / y) * y` (using infinite | ||
| /// precision arithmetic, then rounded to the result type). This is | ||
| /// the IEEE 754 remainder as implemented by C's `fmod`. |
There was a problem hiding this comment.
I would simplify the rounding to:
... as the exact value
x - trunc(x / y) * y. Note that the exact value differs from the Rust expressionx - (x / y).trunc() * yfor some inputs.
| /// precision arithmetic, then rounded to the result type). This is | ||
| /// the IEEE 754 remainder as implemented by C's `fmod`. |
There was a problem hiding this comment.
754's remainder is C's remainder, no?
|
Reminder, once the PR becomes ready for a review, use |
|
@mango766 ping for the small updates |
Summary
Fixes #133758.
The documentation for
<{f16,f32,f64,f128} as Rem>::rempreviously described the remainder as being "computed as:x - (x / y).trunc() * y", which reads as a literal Rust expression. In reality, the operation is mathematically defined as exactx - trunc(x/y) * y(computed in infinite precision, then rounded to the result type), equivalent to C'sfmod. Evaluating the expression literally in Rust produces different results for many inputs due to intermediate floating-point rounding.For example, as noted in the issue:
This PR:
trunc(x / y)) rather than Rust method syntax, making it clear this is not meant as literal codeThis aligns with the consensus in #133758 and the IEEE 754 / C
fmodsemantics documented in RFC 3514.