puzzled about floats

Neal Becker ndbecker2 at gmail.com
Mon Sep 24 14:13:18 EDT 2007


from math import modf

class nco (object):
    def __init__ (self, delta):
        self.delta = delta
        self.phase = 0.0
    def __call__ (self):
        self.phase += self.delta
        f,i = modf (self.phase)
        print  modf (self.phase)
        if (self.phase > 1.0):
            self.phase -= 1.0
        return self.phase

n = nco (0.1)
for x in xrange (100):
    print '%.12f' % n()

prints out
[...]
(0.99999999999999978, 0.0)   <<< from modf
1.000000000000   << from n()

I'm baffled as to why 'print modf (self.phase)' prints out the first value,
but the result printed in the 2nd case is different.  Without any precision
spec on the first print, an approximate float value was printed, but even
with %.12f, the second gives exactly 1.000....




More information about the Python-list mailing list