1

When using the normal division

9999999999999999 / 2

returned value: 5000000000000000.0

and when using the floor division

9999999999999999 // 2

returned value: 4999999999999999

I am using python 3.8.1 can anyone explain this ? Thanks in advance

  • Related, but not really an exact duplicate: https://stackoverflow.com/questions/35897621/why-1-0-05-results-in-19-0-in-python/35906988 – dan04 Nov 19 '21 at 01:33
  • 1
    Also see: https://docs.python.org/3/library/sys.html#sys.float_info. Especially `dig`. You probably have `dig == 15`, which is smaller than the number of digits of `9999999999999999`; try `float(9999999999999999)` for example. – j1-lee Nov 19 '21 at 01:34
  • [Is floating point math broken?](https://stackoverflow.com/q/588004/364696) (Answer: Yes, for a certain definition of "broken"; floating point is the Devil, and you found yet another way in which it is unreliable) – ShadowRanger Nov 19 '21 at 14:01

1 Answers1

3

The / operator on int operands returns a float. Assuming an IEEE 754 compatible system, a float has 53 bits of precision. Thus, it cannot exactly represent the quotient 4999999999999999.5, which would require 54 bits (10001110000110111100100110111111000000111111111111111.1). So this value gets rounded up to 5000000000000000.0.

The // operator on int operands returns an int. The Python 3 int type has unlimited range, so can represent 9999999999999999 exactly. Halving this number gives 4999999999999999 (with a discarded remainder of 1).

dan04
  • 87,747
  • 23
  • 163
  • 198
  • 3
    "So this value gets rounded up to 1e+16" <- This is a common misconception, but it isn't actually what happens: Python (at least, CPython) doesn't convert both arguments to float and then divide the floats. Instead, it directly computes the closest float to the true value of the mathematical quotient. You can see the difference with examples like `10**40 / 10**30`, which Python will compute as `10.0`, while `float(10**40) / float(10**39)` ends up being just a little bit off at `0x1.4000000000001p+3`. (Similarly, `10**1000 / 10**900` would overflow if both values were converted to float first.) – Mark Dickinson Nov 19 '21 at 08:23
  • 1
    Here's the description of the method used: https://github.com/python/cpython/blob/4575c01b750cd26377e803247c38d65dad15e26a/Objects/longobject.c#L3790-L3875 – Mark Dickinson Nov 19 '21 at 08:24
  • 1
    @MarkDickinson: In this specific case, it doesn't make a difference, since dividing by 2 is an exact operation. But I've edited my answer to clarify that the 53-bit limit applies to the final quotient rather than the operands. – dan04 Nov 19 '21 at 14:00