6
votes

Possible Duplicate:
Python rounding error with float numbers

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?

2
floating points do not cover all real numbers, how could they? In any non-trivial range there are infinite number of real (and even rational) numbers, but only finite number of bits to represent them. So the python's math is correct - for floating points arithmetics. - amit
Read the section 14.1 of this link: docs.python.org/tutorial/floatingpoint.html - mvillaress
Python maths is not wrong. You don't understand the representation of floating-point numbers on computers nor the arithmetic of such numbers. Read the resources suggested by other commenters. - High Performance Mark
Python maths is wrong, mathematically speaking. It's just that being perfectly right all the time is computationally infeasible (numbers like sqrt(2) aren't even representable in a finite amount of space without directly coding them as things like sqrt(2)). The errors in Python's floating point arithmetic have been accepted as "the way it is done" for a very long time, and we just have to live with that as a matter of pragmatism. It is very very important for programmers to be aware of this, but we all have this moment of confusion. - Ben
All the delete voters, please don't delete a question that serves as a great signpost to users experiencing similar problems - jamylak

2 Answers

365
votes

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.

53
votes

For a painfully-rigorous guide to how floating-point arithmetic works, complete instructions on how to calculate how large the errors in your answers will be, you need:

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Once you've read that, you should go and look for notes on the 8087 specifically, because it implements IEEE 754 poorly and this can cause new exciting problems in your life.