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

问题描述 投票:7回答:1
>>> 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似乎没有同样的问题。

python numpy long-integer sqrt
1个回答
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

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

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

编辑:好吧,你正在使用Python 3.虽然在该版本中intlong has disappeared之间的区别,NumPy仍然对使用PyLongObject可以成功转换为C longPyLong_AsLong和不能使用qazxswpoi的qazxswpoi之间的差异敏感。

© www.soinside.com 2019 - 2024. All rights reserved.