[Python-3000] bug in modulus?
Antoine
antoine at pitrou.net
Wed May 3 14:23:54 CEST 2006
Le mercredi 03 mai 2006 à 04:41 -0700, Michael Chermside a écrit :
> Tim Peters writes:
> > IMO, it was a mistake (and partly my fault cuz I didn't whine early)
> > for Python to try to define % the same way for ints and floats.
> [...]
> > I'd like to see this change in Python 3000. Note that IBM's proposed
> > standard for decimal arithmetic (which Python's "decimal" module
> > implements) requires two operations here, one that works like
> > math.fmod(a, b) (exact and sign of a), and the other as described
> > above (exact and |a%b| <= |b/2|).
>
> So why not make "x % y" for floats behave exactly
> like it does for integers
It already does :-)
> and provide a separate operation with your
> described behavior?
A common use case is to transform an angle into its normalized value
between -pi and pi.
So why not define math.normalize:
def normalize(a, b):
""" Normalize a between -b/2 and b/2. """
half = b * 0.5
return (a + half) % b - half
>>> normalize(0.4, 1)
0.40000000000000002
>>> normalize(0.6, 1)
-0.39999999999999991
>>> normalize(1.6, 1)
-0.39999999999999991
>>> normalize(1.4, 1)
0.39999999999999991
>>> normalize(-1.4, 1)
-0.39999999999999991
>>> normalize(-0.6, 1)
0.40000000000000002
More information about the Python-3000
mailing list