2
$\begingroup$

In the following program where I repeatedly half an integer, it takes until i = 1074 for my integer to be equal to zero (I know that ideally the while loop shouldn't have ended, and the reason why it stopped was because of the memory limit of the computer).

a = 1.0
i = 0
while a != 0:
    a = a / 2
    i = i + 1
    print(a, i)

However, the next program, where I compare the halved integer using addition ends at i = 53.

a = 1.0
b = 1.0
i = 0
while a + b != b:
    a = a / 2
    i = i + 1
    print(a, i)

My question is why is there a big difference here? Why does the first program go up to 1075 iterations, while the latter goes up to 53?

Also, when I tried a + b + c != b + c, it went up to just 52, furthermore

a + b + c + d != b + c + d

only went up to 51. Why isn't there a big difference here?

$\endgroup$
  • 1
    $\begingroup$ You have print statements already there. What do they print? Once you see what's printed it should be obvious. And of course this has nothing whatsoever to do with "memory limits". And of course you are not doing the same thing. $\endgroup$ – gnasher729 Jan 24 at 22:06
3
$\begingroup$

The reason you are seeing these results are not due to the memory limits of your computer, but rather of the limits of the encoding of "floating point" numbers. Python uses 64 bit floats (aka double precision floating point numbers), which are well described on wikipedia: https://en.wikipedia.org/wiki/Double-precision_floating-point_format

In short, there are only 52 bits for the significand and 11 bits for the exponent. $2^{1023}$ is the highest exponent that can be represented.

| cite | improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.