1

53/24 results 2.2083333333333335 in python.Why is that?

2 Answers2

1

The binary floating-point format Python uses cannot represent 53/24 exactly - but the decimal format most humans learn can't represent 53/24 exactly either. 2.2083333333333333 would still be wrong. It's just that when Python's slightly wrong binary result is translated into decimal, the result isn't the same slightly wrong result you'd get if you did the math in decimal.

user2357112
  • 260,549
  • 28
  • 431
  • 505
0

Floating point numbers in Python rely on binary representations:

Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine.

Playing along with the docs and using decimal, things become a bit more clear (I'm using Python 2.7, hence the cast of the numerator to float):

In [1]: from decimal import Decimal

In [2]: Decimal(53.0 / 24)
Out[2]: Decimal('2.208333333333333481363069950020872056484222412109375')

So, that's why you get the result that you get.

Alternatively, you can also use str.format to take a peek at more decimal places:

In [3]: "{:0.20f}".format(53.0 / 24)
Out[3]: '2.20833333333333348136'

Also, see What Every Programmer Should Know About Floating-Point Arithmetic.