2.6.1 - simple division

Lie Ryan lie.1296 at gmail.com
Mon Mar 9 07:42:49 CET 2009


Duncan Booth wrote:
> 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.
> 
> 

You should also keep fractions.Fraction (Rational) number in your 
toolbox. Rational is the most accurate, though it still can't represent 
irrational numbers[1] (e.g. pi, e, phi, sqrt(2)) and is generally slower 
than the others.

[1] actually, neither float nor Decimal can represent irrationals.

PS: Actually, I've been thinking about reducing numbers that can't be 
represented as float, Decimals, Rationals by adding such things as surds 
and special constants. Basically getting python to have exact arithmetic 
library, but I think it'll be too large and complex while not many 
people really need exact arithmetic.



More information about the Python-list mailing list