np.sqrt对超大整数的异常行为

9 投票
1 回答
1439 浏览
提问于 2025-04-17 18:57
>>> np.__version__
'1.7.0'
>>> np.sqrt(10000000000000000000)
3162277660.1683793
>>> np.sqrt(100000000000000000000.)
10000000000.0
>>> np.sqrt(100000000000000000000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: sqrt

嗯... AttributeError: sqrt 这是怎么回事呢? math.sqrt 似乎没有这个问题。

1 个回答

10

最后得到的数字是一个 long 类型(在Python中,这种类型可以表示任意大小的整数),而NumPy似乎无法处理这种类型:

>>> type(100000000000000000000)
<type 'long'>
>>> type(np.int(100000000000000000000))
<type 'long'>
>>> np.int64(100000000000000000000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long

出现 AttributeError 错误是因为NumPy遇到了它不知道怎么处理的类型,结果默认尝试在这个对象上调用 sqrt 方法;但这个方法并不存在。所以问题不在于 numpy.sqrt 缺失,而是 long.sqrt 不存在。

相比之下,math.sqrt 是知道 long 的。如果你打算在NumPy中处理非常大的数字,尽量使用浮点数(floats)。

编辑:好的,你在使用Python 3。在这个版本中,intlong 之间的区别已经消失了,但NumPy仍然对能成功转换为C语言中的 longPyLongObject 和不能转换的类型很敏感。

撰写回答