working of round()
collinstocks at gmail.com
Mon Apr 16 07:56:51 CEST 2007
On Apr 15, 8:06 pm, Krishna.K.1... at gmail.com wrote:
> Does round() always perfectly return the output expected or are there
> some artifacts which don't allow perfect functionality
> Using python 2.5:
> >>> round(12.234, 2)
> >>> round(12.234, 3)
> >>> round(12.234, 1)
> but was expecting 12.2
> Also, for round(x,n), can't 'x' be an expression
> round(5.25/2, 2)
> was expecting 2.62 , but
> >>> round(5.25/2, 2)
The problem is that floats are encoded as fractions where the
denominator is an exponent of 2.
2.63 is not representable as such a fraction.
2.629999999999999999999999999999999999... is the closest fraction.
Rounding this number will only give you the same thing.
If you want decimals to act as expected, use the Decimal class in
module decimal. It works as expected, but is much slower.
More information about the Python-list