puzzled about floats

N

Neal Becker

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

Marc 'BlackJack' Rintsch

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

Tuples are printed with calling `repr()` on the objects:

In [144]: str(0.1)
Out[144]: '0.1'

In [145]: repr(0.1)
Out[145]: '0.10000000000000001'

In [146]: '%.12f' % 0.1
Out[146]: '0.100000000000'

In [147]: '%.50f' % 0.1
Out[147]: '0.10000000000000000555111512312578270211815834045410'

Ciao,
Marc 'BlackJack' Rintsch
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,588
Members
45,095
Latest member
EmiliaAlfo

Latest Threads

Top