gpt4 book ai didi

python - 为什么 python 不能在所有领域处理非常大的数字?

转载 作者:太空狗 更新时间:2023-10-30 00:37:06 25 4
gpt4 key购买 nike

我正在做一个谜题,我必须处理 10^18 阶的数字。但是,我发现 python 无法在所有领域处理非常大的数字。

具体来说,如果我们分配 a = 1000000000000000000 (10^18) 并进行基本算术计算(+、-、/、*),它会响应。但是,当我在 range() 中使用它时它显示 OverflowError

>>> a = 1000000000000000000
>>> a/2
500000000000000000L
>>> a*2
2000000000000000000L
>>> a+a
2000000000000000000L
>>> a*a
1000000000000000000000000000000000000L
>>> range(a)

Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
range(a)
OverflowError: range() result has too many items
>>> xrange(a)

Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
xrange(a)
OverflowError: Python int too large to convert to C long

我使用的是 Python 2.7。

  1. 我该如何处理此类情况?,处理包含此类数字的谜题的最佳方法是什么。 (教程/书籍引用将不胜感激)
  2. 为什么 Python 无法在 range()/xrange() 中处理它

我想在 python 2.7 中使用内置函数来完成它。这不可能吗?

最佳答案

在 Python 2.x 中,rangexrange 仅限于使用 C long 并且您的大整数对于它来说太大了.此限制仅仅是由于为 rangexrange 做出的实现选择。

在 Python 3.x 中,限制已被移除,您可以使用非常大的整数执行 range()

>>> range(2**128)
range(0, 340282366920938463463374607431768211456)

official list of changes for Python 3 是这样说的:

range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists.


在 Python 2.x 中,range() 函数返回一个列表。显然,不可能为范围非常大的所有元素分配内存。 xrange() 函数返回一个 xrange 对象。 documentation 将其描述为“一种不透明的序列类型,它产生与相应列表相同的值,但实际上并没有同时存储它们”。文档接着说:

xrange() is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs (“short” Python integers), and also requires that the number of elements fit in a native C long.

这解释了 Python 2.x 中的限制。


我不太确定您可以使用新的 Python 3 支持非常大的范围来做什么。例如,我不建议您尝试这样做:

2**128 in range(2**128)

那会运行很长时间。


您在评论中指出您正在编写代码来统计一个大数。您可以使用如下代码在 Python 中简单地执行此操作:

i = 0
while i<N:
doSomething(i)
i += 1

但是您会发现,如果N 是一个很大的数字,那么这将花费很长时间。根据您的问题,对于订单 218N 值,没有任何解决方法。

关于python - 为什么 python 不能在所有领域处理非常大的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8972002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com