round function problem

Fredrik Lundh fredrik at pythonware.com
Tue Sep 6 03:52:34 EDT 2005


"mg" wrote:

> We try to white scripts with Pyrhon 2.4 for an acoustic simulation and
> we wrote these follow lines :
>
> <begin script>
> c = 340
> i =j=k= 1
> sum_ = 23
> table = []
> freq = round((c/2*(sum_)**0.5),2)
> print freq
> table.append([freq,(i,j,k)])
> print i,j,k,' freq',freq
> for item in table: print item
> <end script>
>
> 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 ?!?!?!?!...

round() takes a floating point number, and returns a floating point numbers,
so you're still subject to the issues described in appendix B of the tutorial:

    http://www.python.org/doc/current/tut/node16.html

(note that when you print a plain variable, Python use the "str()" operator,
but when you print it as part of a container, it uses the "repr()" operator on
all members.  repr() gives you more significant digits; see the above link
for details)

to get proper rounding, use the "%" operator to convert the number to a
string.  e.g.

    print "%d %d %.2f" % tuple(item)

see also

    http://www.python.org/doc/current/tut/node9.html
    http://www.python.org/doc/current/lib/typesseq-strings.html

</F> 






More information about the Python-list mailing list