Saturday, January 16, 2010

Floating point arithmetic in Python 3 is much more accurate

There is always limited precision in floating point arithmetic due to conversion between decimal and binary. But I found Python 3 becomes much more accurate.

 zhao@nettop:~$ python  
 Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)   
 [GCC 4.4.1] on linux2  
 Type "help", "copyright", "credits" or "license" for more information.  
 >>> 12.6 / 2  
 6.2999999999999998  
 >>> 12.6 + 0.01
 12.609999999999999
 >>> float('3.2')
 3.2000000000000002  

 zhao@nettop:~$ python3  
 Python 3.1.1+ (r311:74480, Nov 2 2009, 14:49:22)   
 [GCC 4.4.1] on linux2  
 Type "help", "copyright", "credits" or "license" for more information.  
 >>> 12.6 / 2  
 6.3  
 >>> 12.6 + 0.01  
 12.61  
 >>> float('3.2')  
 3.2  
Who has any idea about this?

Update on 27/12/2020, Python 2.7 fixed it as well.
 $ python
 Python 2.7.18rc1 (default, Apr  7 2020, 12:05:55) 
 [GCC 9.3.0] on linux2
 Type "help", "copyright", "credits" or "license" for more information.
 >>> 12.6 / 2
 6.3
 >>> 12.6 + 0.01
 12.61
 >>> float('3.2')
 3.2

No comments:

Post a Comment