0

In python when we add 0.2+0.1

   0.2+0.1
   0.30000000000000004

Also

   3*0.1
   0.30000000000000004

I have tried other combinations and they work fine. Except for these two syntaxes. Can somebody tell me why the interpreter is behaving so strangely?

  • This is not Python-specific *at all*; it's the case in C, or even when using your CPU's built-in floating point calculation support directly in assembly or hand-assembled machine code. – Charles Duffy Apr 07 '20 at 17:10
  • ...though there is a Python-specific workaround; see the [`decimal` module](https://docs.python.org/3/library/decimal.html). – Charles Duffy Apr 07 '20 at 17:10
  • Very, *very* short answer: Remember that your computer uses base-2, not base-10. Not all values can be precisely described in all systems; some values' representations are necessarily inexact. For a long answer, see the links above the question. – Charles Duffy Apr 07 '20 at 17:14
  • It is mentioned and explained in [the official documentation](https://docs.python.org/3/tutorial/floatingpoint.html#representation-error). – Jongware Apr 07 '20 at 17:29

0 Answers0