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?

5
  • 1
    it has to do with how floating point numbers are represented. not limited to python. see docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html Commented Dec 11, 2014 at 6:38
  • floating-point-gui.de Commented Dec 11, 2014 at 6:43
  • If its annoying you, use ipython and set numeric precision, e.g. %precision %.4g Commented Dec 11, 2014 at 6:44
  • Yes we can use %precision .4f% but I preferred using round(2.05*100) which gives 205.0. Commented Dec 11, 2014 at 6:56
  • possible duplicate of Is floating point math broken? Commented Dec 11, 2014 at 7:12

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Epsilon value is the same. But why does 2.04 * 100 returns 204.0 instead of 204.999997.
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).
No worries at all @AmarKamthe, glad I could help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.