[Tutor] flow problem with a exercise
Evert Rol
evert.rol at gmail.com
Sat Aug 21 12:39:05 CEST 2010
> In [39]: t = 3
>
> In [40]: round((t-32)/1.8)
> Out[40]: -16.0
>
> In [41]: t = 3.0
>
> In [42]: round((t-32)/1.8)
> Out[42]: -16.0
>
> Works fine for me.
>
> Correct,
> But I see one wierd thing.
>
> round ((42-32)/1.8) gives a output -16.0 but (42-32)/1.8) gives also -16.0
> I was expectting that round will give 16 as output because round (32.0) is the same as round (32.0, 0) so there will be 0 decimals.
> And I see one decimal.
The rounding doesn't influence how it's printed.
From help(round):
"""
round(...)
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number. Precision may be negative.
"""
It *rounds* the number to ndigits, not prints. It always returns a floating point number though (not an integer).
Since floats are normally represented with at least one trailing digit after the decimal dot, you see a zero.
Eg,
>>> float(1)
1.0
If you want to get rid of the trailing .0, convert it to an integer:
>>> int(round(1.1))
1
Also consider:
>>> round(1.15, 0)
1.0
>>> round(1.15, 1)
1.2
>>> round(1.15, 2)
1.1499999999999999
(Note again how the last rounded 1.15 is represented. It's just a representation though, and showing the imprecision you intrinsicaly get when dealing with floating point numbers.)
If you really want different behaviour when printing (or using) floating point numbers, perhaps have a look at the decimal module: http://docs.python.org/library/decimal.html
More information about the Tutor
mailing list