我有一个numpy一维数组c,应该填充内容
a + b.我首先a + b在使用的设备上执行PyOpenCL.
我想c使用numpy切片快速确定python中结果数组的正确性.
这就是我现在拥有的
def python_kernel(a, b, c):
temp = a + b
if temp[:] != c[:]:
print "Error"
else:
print "Success!"
Run Code Online (Sandbox Code Playgroud)
但我得到错误:
ValueError:具有多个元素的数组的真值是不明确的.使用a.any()或a.all()
但似乎a.any或a.all将只确定值是否不为0.
我应该怎么做,如果我想测试,如果所有的缩放器numpy阵列temp都等于在每个值numpy阵列c?
Amb*_*ber 50
为什么不直接使用 NumPy函数中的numpy.array_equal(a1, a2)[docs]?
Aka*_*all 12
如果np.array数据类型是浮点数,则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])
Run Code Online (Sandbox Code Playgroud)
结果:
>>> 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'
Run Code Online (Sandbox Code Playgroud)
您可以调用any比较结果:if 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
Run Code Online (Sandbox Code Playgroud)
尽管如此,Amber的解决方案可能更快,因为它不必创建整个布尔结果数组.
| 归档时间: |
|
| 查看次数: |
46529 次 |
| 最近记录: |