Possible Duplicate:
Floating Point Limitations
Using Python 2.7 here.
Can someone explain why this happens in the shell?
>>> 5.2-5.0
0.20000000000000018
Searching yielded things about different scales of numbers not producing the right results (a very small number and a very large number), but that seemed pretty general, and considering the numbers I’m using are of the same scale, I don’t think that’s why this happens.
EDIT: I suppose I didn’t define that the “this thing happening” I meant was that it returns 0.2 … 018 instead of simply resulting in 0.2. I get that print rounds, and removed the print part in the code snippet, as that was misleading.
You need to understand that 5.2-5.0 really is 0.20000000000000018, not 0.2. The standard explanation for this is found in What Every Computer Scientist Should Know About Floating-Point Arithmetic.
If you don’t want to read all of that, just accept that 5.2, 5.0, and 0.20000000000000018 are all just approximations, as close as the computer can get to the numbers you really way.
Python has some tricks to allow you to not know what every computer scientist should know and still get away with it. The main trick is that
str(f)—that is, the human-readable rendition of a floating-point number—is truncated to 12 significant digits, sostr(5.2-5.0)is"0.2", not"0.20000000000000018". But sometimes you need all the precision you can get, sorepr(f)—that is, the machine-readable rendition—is not truncated, sorepr(5.2-5.0)is"0.20000000000000018".Now the only thing left to understand is what the interpreter shell does. As Ashwini Chaudhary explains, just evaluating something in the shell prints out its
repr, while theprintstatement prints out itsstr.