0

Does anyone have an idea why this is happening?

>>> 289.6*(100-50)
14480.000000000002

it should give just 14480 !!

I tried something else and it confused me more

>>> 289.6*10*5
14480.0

so why the first one gives 14480.000000000002 and the second gives 14480.0 while it is the same!

Mahmoud Adel
  • 1,262
  • 2
  • 13
  • 23

3 Answers3

3

This is because of floating point precision. In fact, 0.3 - 0.2 != 0.1, because computers use binary instead of decimal. Here's a link explaining why.

If you really need precision, you can use the decimal library:

>>> from decimal import Decimal
>>> Decimal("289.6")*(100-50)
Decimal('14480.0')

sebtheiler
  • 2,159
  • 3
  • 16
  • 29
2

python converts up to float because of your 289.6. if you want an int, try int(289.6*(100-50)) and that will cast the answer to int.
The reason your result has the crazy .0000000002 at the end is because of how floats are stored in computers. For a more in depth read on that, read this

Josh
  • 318
  • 2
  • 8
2

Take a look here: https://docs.python.org/3/tutorial/floatingpoint.html

The gist of it is that floating-point numbers are approximations. In your case, this is probably an approximation of a binary number, displayed as a decimal one.

Itay Vegh
  • 51
  • 4
  • You have it backwards. The number is binary, but it's approximating a decimal one. It's possible to display a binary number precisely in decimal, but it takes a lot more digits than you expect. – Mark Ransom Jun 30 '21 at 00:03