Search code examples
pythonmathnumbers

Python floating-point math is wrong


Python 2.7.3 (v2.7.3:70274d53c1dd, Apr  9 2012, 20:52:43) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> 4.2 - 1.8
2.4000000000000004
>>> 1.20 - 1.18
0.020000000000000018
>>> 5.1 - 4
1.0999999999999996
>>> 5 - 4
1
>>> 5.0 - 4.0
1.0

Why is Python getting its maths wrong?


Solution

  • You have reached a new level in computer science, and you are coming of age.

    You therefore are now ready for the next step. I have been authorized by the BDFL himself to reveal the following Super Secret document to you. The ancients understood it and deciphered it first, and now, so will you!

    The Floating Point Guide

    Treat this document with care! Only share this with people you know have reached the same baffling conclusions!


    Moderator's Note

    This answer is not representative of the expected quality standards on Stack Overflow. However, it has unexpectedly developed a life of its own and is solely preserved for historical significance now.