Very odd python behaviour where integers overflow inside a nested for loop, but not outside of it

  integer, overflow, python

I have no idea what the hell is going on here, but here is a relevant code snippet

import random

def random_with_N_digits(n):
    range_start = 10**(n-1)
    range_end = (10**n)-1
    print(range_start)
    print(range_end)
    return random.randint(range_start, range_end)

if __name__ == "__main__":
    digits = np.arange(3,16,1, dtype = int)
    for i in digits:
        for j in range(5):
            a = random_with_N_digits(2**i)
            b = random_with_N_digits(2**i)

Those print statements are just for debugging. For whatever reason, when i = 4 or higher, I start to get integer overflow problems. Oddly, if I put print(10**32) anywhere in my code that works perfectly. Hell, even if I copy the bulk of the random_with_N_digits code (except for the return statement with the random.randint bit) it produces the expect result with n = 32.

I am at a loss for what is going on here. It is some subtle type thing in the python back-end that is hidden away from me?

EDIT: I don’t know why, but if I change 2**i to 32 or some other integer, it works. I have absolutely no clue why that happens, and it also isn’t optimal as I need that 2**i in my code. What the heck.

Source: Python Questions

LEAVE A COMMENT