Problems using modulo

Griff griffph at aol.com
Mon Apr 19 11:31:20 EDT 2004


Test program:
===============================================================
t = 5.8
interval = 2.0

while t < 6.1:
    print "%s mod %s = %s " % (t, interval, t % interval )
    t += 0.1
================================================================
Results:
5.8 mod 2.0 = 1.8
5.9 mod 2.0 = 1.9
6.0 mod 2.0 = 2.0 !!!!!!
6.1 mod 2.0 = 0.1

=================================================================

if we change t to initialise at 5.9 and run the program again,

=================================================================

t = 5.9
interval = 2.0

while t < 6.1:
    print "%s mod %s = %s " % (t, interval, t % interval )
    t += 0.1
=================================================================
Results:

C:\Python22>python modprob.py
5.9 mod 2.0 = 1.9
6.0 mod 2.0 = 0.0   # that's better

====================================================

I have tried this on Windows and Unix for Python versions between 1.52
and 2.3.

I don't know much about how Python does its floating point, but it
seems like a bug to me ?

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).

Would be grateful for any suggestions 

cheers

- Griff



More information about the Python-list mailing list