Problems using modulo

Brian Gough bjg at network-theory.co.uk
Mon Apr 19 12:12:20 EDT 2004


griffph at aol.com (Griff) writes:

> Results:
> 5.9 mod 2.0 = 1.9
> 6.0 mod 2.0 = 2.0 !!!!!!
> 6.1 mod 2.0 = 0.1
> 
> I don't know much about how Python does its floating point, but it
> seems like a bug to me ?

This is a common "feature" of floating-point arithmetic.  0.1 does not
have an exact machine representation in binary, so the numbers
displayed are not exact (e.g. 6.0 is actually 5.9999999... with a
difference O(10^-15)).  There is an appendix in the Python tutorial
which discusses this, with more examples.

> What is the best workaround so that I can get my code working as
> desired ?
> (ie I just want to tell whether my time "t" is an exact multiple of
> the time interval, 2.0 seconds in this case).

For exact arithmetic, work with integers (e.g. in this case multiply
everything 10) or compute the difference from zero in the modulus, d,

  s = t % interval
  d = min (s, interval-s)

and compare it with a small tolerance, e.g. 1e-10 or something
appropriate to your problem. HTH.

-- 
Brian Gough

Network Theory Ltd,
Publishing Python Manuals --- http://www.network-theory.co.uk/



More information about the Python-list mailing list