2011-08-18 57 views
15

我有一個numpy一維數組c,應該填充 a + b的內容。我首先在使用PyOpenCL的設備上執行a + b測試numpy數組中的所有值是否相等

我想快速確定結果數組c在Python中使用numpy切片的正確性。

這是我目前有

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 array c

+2

'all_values_are_same =所有(your_array [0] == your_array):'什麼,做是如果每個值等於所述第一值返回布爾的列表,並聲稱所有這些都是真實的。 –

回答

49

爲什麼不直接使用NumPy的功能中的numpy.array_equal(a1, a2)[docs]

+3

你可以檢查array_equal()的源代碼,並且因爲它調用equal(),它也創建整個布爾向量。 – HYRY

7

您可以在比較結果上撥打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可能更快,因爲它沒有創建整個布爾結果陣列。

10

np.allclose是一個不錯的選擇,如果np.array數據類型是浮點數。 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' 
+0

這讓我很頭疼,很高興知道有'np.array_equal'炸彈與浮筒。謝謝! – Gabriel

+1

通常的浮點精度錯誤。我不會責怪'array_equal'在這裏工作不正確。它做它應該做的事情。任何是的,'allclose'是你打算做的正確選擇。 – Michael

相關問題