Python -- floating point arithmetic

Philip Semanchuk philip at semanchuk.com
Wed Jul 7 10:05:22 EDT 2010


On Jul 7, 2010, at 9:08 AM, Thomas Jollans wrote:

> On 07/07/2010 02:05 PM, david mainzer wrote:
>> today i create some slides about floating point arithmetic. I used an
>> example from
>>
>> http://docs.python.org/tutorial/floatingpoint.html
>>
>> so i start the python shell on my linux machine:
>>
>> dm at maxwell $ python
>> Python 2.6.5 (release26-maint, May 25 2010, 12:37:06)
>> [GCC 4.3.4] on linux2
>> Type "help", "copyright", "credits" or "license" for more  
>> information.
>>>>>>>> sum = 0.0
>>>>>>>> for i in range(10):
>> ...     sum += 0.1
>> ...
>>>>>>>> sum
>> 0.99999999999999989
>>>>>>>>
>> But thats looks a little bit wrong for me ... i must be a number  
>> greater
>> then 1.0 because 0.1 =  
>> 0.100000000000000005551115123125782702118158340454101562500000000000
>> in python ... if i print it.
>
> The simple fact of the matter is: floating point arithmetic isn't
> accurate. This has nothing to do with Python, it's the fault of your
> processor's floating point handling. It's good enough in most cases,  
> but
> you should never rely on a floating-point number to have exactly a
> certain value. It won't work.

Yes, this might be a good time to review the dense but interesting  
document, "What Every Computer Scientist Should Know About Floating- 
Point Arithmetic":
http://docs.sun.com/source/806-3568/ncg_goldberg.html


Cheers
Philip








More information about the Python-list mailing list