[Tutor] Hummm...dubious behavior.
alan.gauld@bt.com
alan.gauld@bt.com
Mon, 17 Dec 2001 16:01:00 -0000
> >>> 0.6125
> 0.61250000000000004
> >>>
>
> occurs because of the fact, that the number 0.6125
> is not a power of 2 (or 1/2) and so the internal
> binary representation of it *has* to be
> an approximation of it.
Correct. And round is not intended to change the
printed representation of the numbers but to change
the actual value of the number.
To change the representation use string formatting
codes
Thus:
>>> print "%5.3" % math.pi
3.142
ie 5 characters with 3 after the decimal point.
> (Maybe this has something to do with the difference
> between __repr__ and __str__ (?) )
Yes again. The interpreter uses one, print uses the other.
(I can't remember which is which, I thing print uses str...)
> >>> print 0.6125, 4.1225
> 0.6125 4.1225
> >>> print (0.6125, 4.1225)
> (0.61250000000000004, 4.1224999999999996)
No, its consistent, one is the __str__ of a number the
other is the __str__ of a tuple. Its down to how those
__str__ functions work not a discrepency in print.
[ You should be able to verify this by calling the
__str__ and __repr__ functions explicitly, but
I haven't tried... ]
Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld