You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.
IEEE 754, the C99 standard, the Decimal IBM standard and Java all support/specify a 'remainder-near' operation. Apart from being standard, this has a number of useful applications:
Argument reduction in numerical algorithms: it's common to want to reduce to a range [-modulus/2, modulus/2] rather than [0, modulus).
Particular case of the above: reduction of angles to lie in the range [-pi, pi]
Rounding a float x to the nearest multiple of y. This is a much-asked StackOverflow question, and the standard answer of y * round(x / y) risks introducing floating-point error and so can give incorrect results in corner cases. With a remainder operation, it's trivial to do this correctly: x - remainder(x, y) gives the closest representable float to the closest integer multiple of y to x.
remainder(x, y) has some nice properties: it's *always* exactly representable (unlike x % y), it satisfies the symmetry remainder(-x, y) == -remainder(x, y), and it's periodic with period 2*y.
Shouldn't the new function be named math.remainder_near?
Not clear. :-) I'd prefer to keep the name that's consistent with both C and IEEE 754. (We already have plenty of naming differences between Decimal and math; attempting to reconcile them is likely futile.)