测试numpy数组中的所有值是否为eq

2024-04-20 11:18:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个numpy一维数组c,它应该填充 a + b。我首先使用PyOpenCL在设备上执行a + b

我想使用numpy切片快速确定python中结果数组c的正确性。

这就是我现在拥有的

def python_kernel(a, b, c):
    temp = a + b
    if temp[:] != c[:]:
        print "Error"
    else:
        print "Success!"

但我得到了错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

但似乎a.anya.all将决定这些值是否不是0。

如果我想测试numpy数组temp中的所有标量是否都等于numpy数组c中的每个值,该怎么办?


Tags: pyopenclnumpyifdefany切片error数组
3条回答

如果np.array数据类型是floats,那么np.allclose是一个不错的选择。np.array_equal并不总是正常工作。例如:

import numpy as np
def get_weights_array(n_recs):
    step = - 0.5 / n_recs
    stop = 0.5
    return np.arange(1, stop, step)

a = get_weights_array(5)
b = np.array([1.0, 0.9, 0.8, 0.7, 0.6])

结果:

>>> a
array([ 1. ,  0.9,  0.8,  0.7,  0.6])
>>> b
array([ 1. ,  0.9,  0.8,  0.7,  0.6])
>>> np.array_equal(a, b)
False
>>> np.allclose(a, b)
True

>>> import sys
>>> sys.version
'2.7.3 (default, Apr 10 2013, 05:13:16) \n[GCC 4.7.2]'
>>> np.version.version
'1.6.2'

您可以根据比较的结果调用anyif np.any(a+b != c):或等效的if np.all(a+b == c):a+b != c创建一个由dtype=bool组成的数组,然后any查看该数组中是否有成员是True

>>> import numpy as np
>>> a = np.array([1,2,3])
>>> b = np.array([4,5,2])
>>> c = a+b
>>> c
array([5, 7, 5]) # <---- numeric, so any/all not useful
>>> a+b == c
array([ True,  True,  True], dtype=bool) # <---- BOOLEAN result, not numeric
>>> all(a+b == c)
True

尽管如此,尽管如此,Amber's solution可能更快,因为它不必创建整个布尔结果数组。

为什么不直接使用NumPy函数中的^{}[docs]

相关问题 更多 >