Python3中的整数溢出 [英] Integer overflow in Python3

查看:106
本文介绍了Python3中的整数溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,正在阅读在页面上我看到了一个奇怪的陈述:

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等于大于它的数字吗?我感觉到部队发生了混乱.

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

我知道在Python 3中,整数没有固定的字节长度.因此,没有整数溢出,就像C的 int 的工作方式一样.但是当然,内存不能存储无限的数据.

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.

我认为这就是为什么 n + 1 的结果与 n 相同的原因:Python无法分配更多的内存来执行求和,因此被跳过,并且 n == n 为true.正确吗?

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?

如果这样,可能会导致程序结果不正确.为什么在无法执行操作时Python不会引发错误,就像C ++的 std :: bad_alloc 一样?

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?

即使 n 不太大并且检查结果为false,由于乘法, result 也将需要更多的字节.出于相同原因,结果* =因数可能会失败吗?

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?

我在官方Python文档中找到了它.检查大整数/可能的整数溢出"真的是正确的方法吗?

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

推荐答案

Python3

只有花车有python中的硬限制.整数是在内部实现为任意大小的长"整数对象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

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

出于相同原因,结果* =因数会失败吗?

为什么不尝试呢?

import sys

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

Python有一个特殊的无穷大浮点值(也有负无穷大),如

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

这篇关于Python3中的整数溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆