简体   繁体   English

Python3中的整数溢出

[英]Integer overflow in Python3

I'm new to Python, I was reading this page where I saw a weird statement:我是 Python 新手,我在阅读 这个页面时看到了一个奇怪的声明:

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

x equals to a number greater than it?! x 等于一个大于它的数?! I sense a disturbance in the Force.我感觉到原力中的干扰。

I know that in Python 3, integers don't have fixed byte length.我知道在 Python 3 中,整数没有固定的字节长度。 Thus, there's no integer overflow, like how C's int works.因此,没有整数溢出,就像 C 的int工作方式一样。 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.我认为这就是为什么n+1的结果可以与n相同的原因:Python 无法分配更多内存来执行求和,因此它被跳过,并且n == n为真。 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 ?当操作不可能时,为什么 Python 不会引发错误,就像 C++ 的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.即使n不是太大并且检查评估为假, result - 由于乘法 - 将需要更多字节。 Could result *= factor fail for the same reason? result *= factor会因为同样的原因而失败吗?

I found it in the offical Python documentation.我在官方 Python 文档中找到了它。 Is it really the correct way to check big integers / possible integer "overflow"?检查大整数/可能的整数“溢出”真的是正确的方法吗?

Python3 Python3

Only floats have a hard limit in python.只有浮点数在 python 中有硬限制。 Integers are implemented as “long” integer objects of arbitrary size in python3 anddo not normally overflow .整数在 python3 中被实现为任意大小的“长”整数对象,通常不会溢出

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您可能还想看看sys.float_infosys.maxsize

Python2 Python2

In python2 integers are automatically casted to long integers if too large as described in the documentation for numeric types在 python2 中,如果数字类型文档中描述的太大,整数会自动转换为长整数

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? result *= factor会因为同样的原因而失败吗?

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 Python 有一个特殊的无穷大浮点值(也有负无穷大),如浮点数文档中所述

Integers don't work that way in Python.整数在 Python 中不是这样工作的。

But float does.但浮动确实如此。 That is also why the comment says 1e300 , which is a float in scientific notation.这也是为什么评论说1e300 ,这是科学计数法中的浮点数。

I had a problem of with integer overlflows in python3, but when I inspected the types, I understood the reason:我在 python3 中遇到了整数溢出的问题,但是当我检查类型时,我明白了原因:

import numpy as np

a = np.array([3095693933], dtype=int)
s = np.sum(a)
print(s)
# 3095693933
s * s
# -8863423146896543127
print(type(s))
# numpy.int64
py_s = int(s)
py_s * py_s
# 9583320926813008489

Some pandas and numpy functions, such as sum on arrays or Series return an np.int64 so this might be the reason you are seeing int overflows in Python3.一些 pandas 和 numpy 函数,例如数组上的sum或 Series 返回 np.int64,因此这可能是您在 Python3 中看到 int 溢出的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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