[Tutor] Python 2.5.4 - error in rounding

Steven D'Aprano steve at pearwood.info
Sat May 22 14:32:10 CEST 2010


On Sat, 22 May 2010 07:16:20 am wesley chun wrote:
> correct, it is a floating point issue regardless of language.. it's
> not just Python. you cannot accurately represent repeating fractions
> with binary digits (bits). more info specific to Python here:
> http://docs.python.org/tutorial/floatingpoint.html
>
> also, keep in mind that '%f' is not a rounding operation... it just
> converts floats to strings. if you want to round, you need to use
> both string formatting as well as the round() built-in function.
>
> finally, +1 on using decimal.Decimal as necessary comfortwise.

Why do people keep recommending Decimal? Decimals suffer from the exact 
same issues as floats, plus they are slower.

You can't represent all fractions as Decimals either:

>>> from decimal import Decimal
>>> d = Decimal(1)/Decimal(3)
>>> d * 3 == 1
False

If you care about representing fractions exactly, use the fraction 
module, not decimal.


>>> from fractions import Fraction
>>> f = Fraction(1, 3)
>>> f * 3 == 1
True


-- 
Steven D'Aprano


More information about the Tutor mailing list