2.6.1 - simple division

Duncan Booth duncan.booth at invalid.invalid
Sun Mar 8 11:34:50 EDT 2009


farsight at gmail.com wrote:

> Thanks all, that's very helpful, sorry to waste your time with a
> common question. I have tried the decimal module and will definitely
> keep using it if I need to do this kind of calculation again.

Try to remember though that the decimal module simply replaces one source 
of inaccuracies with another one:

>>> Decimal("1")/Decimal("3")
Decimal('0.3333333333333333333333333333')
>>> _ * 3
Decimal('0.9999999999999999999999999999')
>>> 1./3.
0.33333333333333331
>>> _ * 3
1.0

Sometimes you want floating point, sometimes you want Decimal. You need to 
understand the advantages and drawbacks of each in order to make an 
informed choice.

> 
> I have 1 more question that the floating point article that was linked
> didn't really answer:
> 
> >>> x = 0.8
> >>> x
>  0.800000000000004
> >>> x * 5
>  4.0
> 
> Shouldn't I be expecting something like 4.0000000000002 ?
> 

You should certainly expect that the final result may be a little bit away 
from the 'exact' result but rounding errors can work in your favour just as 
well as they work against.





More information about the Python-list mailing list