Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating Point Equality Handling in Python

I'm relatively new to Python, and reading through a tutorial page on the documentation website, I came across this snippet:enter image description here This made me curious, so I decided to type it into a Python file and test it out. When I did this, however, it gave me a different result:

   .1+.1+.1 == .3
=> True

This question may seem trivial, but I'm curious why the actual behavior did not match what the Python documentation said it would do. Any answers?

This behavior occured while using an online interpreter. Running it locally returned False.

like image 309
Jared Nielsen Avatar asked Jan 25 '26 03:01

Jared Nielsen


2 Answers

You never said which version of Python you're running, and that can make a huge difference. The arithmetic is likely to be IEEE based doubles which should be consistent from system to system. However CPython is based on underlying C libraries, and those can vary in the way they round floating-point constants as they're input. Other versions of Python will also be dependent on some underlying platform.

Edit: Confirmed. Using the online interpreter given in the question I get:

   '%0.20f' % (.1+.1+.1,)
=> '0.30000000000000004441'
   '%0.20f' % (.3,)
=> '0.30000000000000004441'

Using Python 2.7 on Windows:

>>> '%0.20f' % (.1+.1+.1,)
'0.30000000000000004441'
>>> '%0.20f' % (.3,)
'0.29999999999999998890'

It appears the online interpreter rounds the input differently.

like image 144
Mark Ransom Avatar answered Jan 26 '26 16:01

Mark Ransom


First comment is the answer. On my system:

Python 2.7.3 (default, Sep 26 2012, 21:53:58) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 0.1+0.1+0.1 == 0.3
False
>>>

from python docs (http://docs.python.org/2/tutorial/floatingpoint.html):

Binary floating-point arithmetic holds many surprises like this. The problem with “0.1” is explained in precise detail below, in the “Representation Error” section. See The Perils of Floating Point for a more complete account of other common surprises.

like image 40
ndpu Avatar answered Jan 26 '26 18:01

ndpu