np.sqrt对于大整数的怪异行为 [英] Weird behaviour of np.sqrt for very large integers
问题描述
>>> 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
似乎没有相同的问题.
Huh... AttributeError: sqrt
what's going on here then? math.sqrt
doesn't seem to have the same problem.
推荐答案
最后一个数字是long
(Python的任意精度整数的名称),NumPy显然无法处理:
The final number is a long
(Python's name for an arbitrary precision integer), which NumPy apparently can't deal with:
>>> 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
.
The AttributeError
occurs because NumPy, seeing a type that it doesn't know how to handle, defaults to calling the sqrt
method on the object; but that doesn't exist. So it's not numpy.sqrt
that's missing, but long.sqrt
.
相比之下,math.sqrt
了解long
.如果您打算在NumPy中处理非常大的数字,请在可行的情况下使用浮点数.
By contrast, math.sqrt
knows about long
. If you're going to deal with very large numbers in NumPy, use floats whenever feasible.
编辑:好的,您正在使用Python3.int
和long
之间的区别 PyLongObject
可以使用
EDIT: Alright, you're using Python 3. While the distinction between int
and long
has disappeared in that version, NumPy is still sensitive to the difference between a PyLongObject
that can be successfully converted to a C long
using PyLong_AsLong
and one that can't.
这篇关于np.sqrt对于大整数的怪异行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!