Answer a question

I'm new to Python, I was reading this page where I saw a weird statement:

if n+1 == n:  # catch a value like 1e300
    raise OverflowError("n too large")

x equals to a number greater than it?! I sense a disturbance in the Force.

I know that in Python 3, integers don't have fixed byte length. Thus, there's no integer overflow, like how C's int works. But of course the memory can't store infinite data.

I think that's why the result of n+1 can be the same as n: Python can't allocate more memory to preform the summation, so it is skipped, and n == n is true. Is that correct?

If so, this could lead to incorrect result of the program. Why don't Python raise an error when operations are not possible, just like C++'s std::bad_alloc?

Even if n is not too large and the check evaluates to false, result - due to the multiplication - would need much more bytes. Could result *= factor fail for the same reason?

I found it in the offical Python documentation. Is it really the correct way to check big integers / possible integer "overflow"?

Answers

Python3

Only floats have a hard limit in python. Integers are implemented as “long” integer objects of arbitrary size in python3 and do not normally overflow.

You can test that behavior with the following code

import sys

i = sys.maxsize
print(i)
# 9223372036854775807
print(i == i + 1)
# False
i += 1
print(i)
# 9223372036854775808

f = sys.float_info.max
print(f)
# 1.7976931348623157e+308
print(f == f + 1)
# True
f += 1
print(f)
# 1.7976931348623157e+308

You may also want to take a look at sys.float_info and sys.maxsize

Python2

In python2 integers are automatically casted to long integers if too large as described in the documentation for numeric types

import sys

i = sys.maxsize
print type(i)
# <type 'int'>

i += 1
print type(i)
# <type 'long'>

Could result *= factor fail for the same reason?

Why not try it?

import sys

i = 2
i *= sys.float_info.max
print i
# inf

Python has a special float value for infinity (and negative infinity too) as described in the docs for float

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐