>>> 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
Huh... AttributeError: sqrt
那么这是怎么回事?math.sqrt
似乎没有同样的问题。
最终的数字是一个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
The AttributeError
发生这种情况是因为 NumPy 看到它不知道如何处理的类型,默认调用sqrt
对象上的方法;但这并不存在。所以这不是numpy.sqrt
缺少那个,但是long.sqrt
.
相比之下,math.sqrt
知道long
。如果您要在 NumPy 中处理非常大的数字,请尽可能使用浮点数。
EDIT:好吧,你使用的是Python 3。虽然两者之间的区别int
and long
已经消失了 http://www.python.org/dev/peps/pep-0237/在该版本中,NumPy 仍然对 a 之间的差异敏感PyLongObject http://hg.python.org/cpython/file/38e263d40d81/Objects/longobject.c可以成功转换为Clong
using PyLong_AsLong http://docs.python.org/3/c-api/long.html#PyLong_AsLong还有一个不能。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)