round function problem

Magnus Lycka lycka at carmen.se
Tue Sep 6 04:45:36 EDT 2005


mg wrote:
> The problem is simple. The function 'round' allow to obtain the value 
> with the specified number of digits after the ",". Then, when the 
> variable 'freq' is printed, there is no problem; but when freq is set in 
> the table and the table printed, all the digits are come back.
> 
> Is it a bug or a control behavour ? I don't understand ?!?!?!?!...

There are two things to consider here:

First of all, a floating point number is binary in nature, and
a rounded floating point number is still a binary number, not
a base ten number. E.g:

 >>> 10/3.
3.3333333333333335
 >>> round(_,1)
3.2999999999999998
 >>> print _
3.3

See? The internal representation of the number roughly consists of a
mantissa and an exponent, so that the mantissa times two to the power
of the exponent gives you the number. Just as you can't represent ten
thirds exactly as a finite decimal number (3.333333333...), you can't
represent 3.3 exactly as a binary floating point number.
3.2999999999999998 is about as close as you get (this is still rounded).

The result of the round() function is still a floating point number,
it's not a string of text or a number internally represented with base
10.

Second, you need to understand that there are two ways of converting
every Python object to a sting representation. You can read about the
str() and repr() functions in the library manual, chapter 2.

When you print a list, you use repr(), which shows you lots of
significant digits for floats.

You can solve your immediate problem by changing "print item" to
print "map(str,item)" or something like that. Perhaps you prefer
print ", ".join(map(str,item))




More information about the Python-list mailing list