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

I was calculating eigenvectors and eigenvalues of a matrix in NumPy and just wanted to check the results via assert(). This would throw a ValueError that I don't quite understand, since printing those comparisons works just fine. Any tips how I could get this assert() working?

import numpy as np
A = np.array([[3,5,0], [5,7,12], [0,12,5]])
eig_val, eig_vec = np.linalg.eig(A)
print('eigenvalue:', eig_val)
print('eigenvector:', eig_vec)

for col in range(A.shape[0]):
    assert( (A.dot(eig_vec[:,col])) == (eig_val[col] * eig_vec[:,col]) )

This question is related to numpy

The answer is


The error message explains it pretty well:

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

What should bool(np.array([False, False, True])) return? You can make several plausible arguments:

(1) True, because bool(np.array(x)) should return the same as bool(list(x)), and non-empty lists are truelike;

(2) True, because at least one element is True;

(3) False, because not all elements are True;

and that's not even considering the complexity of the N-d case.

So, since "the truth value of an array with more than one element is ambiguous", you should use .any() or .all(), for example:

>>> v = np.array([1,2,3]) == np.array([1,2,4])
>>> v
array([ True,  True, False], dtype=bool)
>>> v.any()
True
>>> v.all()
False

and you might want to consider np.allclose if you're comparing arrays of floats:

>>> np.allclose(np.array([1,2,3+1e-8]), np.array([1,2,3]))
True

try this=> numpy.array(yourvariable) followed by the command to compare, whatever you wish to.