Search code examples
pythonpython-3.xfloating-pointintegerlimit

Range of int and float in Python


I have these two small programs:

1.

x = 1000

while (1000 * x != x):
    x = 1000 * x

print("Done")

2.

x = 1000.0

while (1000.0 * x != x):
    x = 1000.0 * x

print("Done")

I am trying to make an informed guess on how these programs would execute. I thought as integers are stored in 4 bytes (32 bits), that the first program will execute the loop until x reaches 2^31 and then maybe give out an error. And I guessed that the second loop would go on forever as floats can store more information than int.

My guess couldn't be any more wrong. The first one seems to go on forever whereas the second exists the loop and prints "Done" after x reaches approximately 10^308–this is when x takes the value inf (presumably infinite).

I can't understand how this works, any explanation would be appreciated. Thank you!


Solution

  • The first example with integers will loop until no memory is available (in which case the process will stop or the machine will swap to death):

    x = 1000
    
    while (1000 * x != x):
        x = 1000 * x
    

    because integers don't have a fixed size in python, they just use all the memory if available (in the process address range).

    In the second example you're multiplying your floating point value, which has a limit, because it's using the processor floating point, 8 bytes (python float generally use C double type)

    After reaching the max value, it overflows to inf (infinite) and in that case

    1000 * inf == inf
    

    small interactive demo:

    >>> f = 10.0**308
    >>> f*2
    inf
    >>> f*2 == f*1000
    True
    >>>