To get the accurate value of 1 - 0.999999999999999 ,how to implement the python algorithm #?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Oct 9 07:39:00 EDT 2012


On Tue, 09 Oct 2012 02:00:04 +1100, Chris Angelico wrote:

> On Tue, Oct 9, 2012 at 1:48 AM, Dave Angel <d at davea.name> wrote:
>> import decimal
>> a = decimal.Decimal(4.3)
>> print(a)
>>
>> 5.0999999999999996447286321199499070644378662109375
> 
> Ah, the delights of copy-paste :)
> 
>> The Decimal class has the disadvantage that it's tons slower on any
>> modern machine I know of...
> 
> Isn't it true, though, that Python 3.3 has a completely new
> implementation of decimal that largely removes this disadvantage?

Yes. It's blazingly fast: up to 120 times faster than the pure Python 
version, and within an order of magnitude of the speed of binary floats:

[steve at ando ~]$ python3.3 -m timeit -s "x, y = 1001.0, 978.0" 
> "x+y-(x/y)**4"
1000000 loops, best of 3: 0.509 usec per loop

[steve at ando ~]$ python3.3 -m timeit -s "from decimal import Decimal" 
> -s "x, y = Decimal(1001), Decimal(978)" "x+y-(x/y)**4"
100000 loops, best of 3: 3.58 usec per loop


Without hardware support, Decimal will probably never be quite as fast as 
binary floats, but its fast enough for all but the most demanding needs.



-- 
Steven



More information about the Python-list mailing list