0
>>> 2.04 * 100
204.0
>>> 2.05 * 100
204.99999999999997

In the above example if you multiple 2.04 by 100 it gives 204.0 and if 2.05 is multiplied by same number it returns 204.99999997. Now if you go on trying for further numbers you will find that 2.06, 2.08, etc. will give the exact number. That means the numbers after multiplying are even will return xxx.0 while the odd numbers will return xxx.999997. Why this is so?

Amar Kamthe
  • 2,524
  • 2
  • 15
  • 24

1 Answers1

3

Oh lucky you, you've hit a milestone in your programming career, floating point numbers.

The short version is that because we can't represent something like 1/10th in base 2 (eventually numbers are stored as binary), programming languages have to create approximations. In this case, Python is trying to be helpful by giving you a reasonable close representation of 2.05 * 100.

When programming and dealing with float values, you can employ an epsilon value for comparison to say "if what I expect and the floating point operation is close enough, consider it true."

You can see what epsilon value your Python install is using by looking in the sys module:

>>> import sys
>>> sys.float_info.epsilon
2.220446049250313e-16
  • Epsilon value is the same. But why does 2.04 * 100 returns 204.0 instead of 204.999997. – Amar Kamthe Dec 11 '14 at 07:15
  • 2.04 * 100 returns 204.0 because it happened to line up with a value that could be represented in base2 (or it was a value that _couldn't_ be represented and it was rounded to the _next possible_ floating point representation, which happened to be 204.0). –  Dec 11 '14 at 07:21
  • No worries at all @AmarKamthe, glad I could help. –  Dec 11 '14 at 07:26