Precision?

Steven Bethard steven.bethard at gmail.com
Sun May 15 10:36:32 EDT 2005


tiissa wrote:
> Steffen Glückselig wrote:
> 
>>>>> 1.0 + 3.0 + 4.6
>> 8.5999999999999996
>>
>> Ehm, how could I get the intuitively 'correct' result of - say - 8.6?
>> ;-)
> 
> You may find annex B of the python tutorial an interesting read:
> http://docs.python.org/tut/node16.html

Yes, the simplest way to get what you are expecting is probably:

py> print 1.0 + 3.0 + 4.6
8.6

The print statement calls str() instead of repr().  In many (most?) 
cases, this will print out what you expect it to.  But you should be 
aware of floating-point representation issues, and you should definitely 
read the reference above.  If you really do need precise decimal 
representation, you can use the 2.4 decimal.Decimal objects:

py> d.Decimal("1.0") + d.Decimal("3.0") + d.Decimal("4.6")
Decimal("8.6")

But if you just want a handy calculator, I'd go with print.

STeVe



More information about the Python-list mailing list