np.sqrt对于大整数的怪异行为 [英] Weird behaviour of np.sqrt for very large integers

查看:234
本文介绍了np.sqrt对于大整数的怪异行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> 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.intlong之间的区别

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆