简体   繁体   中英

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!

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
>>> 

From this article:

When a variable is initialized with an integer value, that value becomes an integer object, and the variable points to it (references the object).

Python removes this confusion, there is only the integer object. Does it have any limits? Very early versions of Python had a limit that was later removed. The limits now are set by the amount of memory you have in your computer. If you want to create an astronomical integer 5,000 digits long, go ahead. Typing it or reading it will be the only problem! How does Python do all of this? It automatically manages the integer object, which is initially set to 32 bits for speed. If it exceeds 32 bits, then Python increases its size as needed up to the RAM limit.

So example 1 will run as long as your computer has the RAM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM