np.sqrt对于大整数的奇怪行为

wim*_*wim 7 python numpy sqrt long-integer

>>> 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
Run Code Online (Sandbox Code Playgroud)

嗯...... AttributeError: sqrt接下来发生了什么? math.sqrt似乎没有同样的问题.

Fre*_*Foo 8

最后的数字是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
Run Code Online (Sandbox Code Playgroud)

AttributeError发生这种情况是因为NumPy看到一个它不知道如何处理的类型,默认调用sqrt该对象上的方法; 但那不存在.所以这不是numpy.sqrt缺少的,而是long.sqrt.

相比之下,math.sqrt知道long.如果您要在NumPy中处理非常大的数字,请尽可能使用浮点数.

编辑:好的,你正在使用Python 3.虽然在那个版本之间的区别intlong 消失已经消失了,但NumPy仍然对PyLongObject可以成功转换为C long使用PyLong_AsLong和不能使用C 之间的区别敏感.