[Tutor] Python 2.5.4 - error in rounding

Lie Ryan lie.1296 at gmail.com
Sun May 23 09:59:03 CEST 2010


On 05/22/10 22:32, Steven D'Aprano wrote:
> 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.

I was recommending Decimal because, to me, the OP seems to want to
control how the rounding done, instead of actually wanting precision.

Decimal is perfectly fine solution if you only want to control the
rounding; using fraction to control rounding is possible, but can be a
little awkward.

Of course, Decimal only gives "predictable rounding", it doesn't really
solve infinite .999.. problems.



More information about the Tutor mailing list