Issue
I was calculating eigenvectors and eigenvalues of a matrix in NumPy and just wanted to check the results via an assert
statement. 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
statement 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])
Solution
As it says, it is ambiguous. Your array comparison returns a boolean array. Methods any() and all() reduce values over the array (either logical_or or logical_and). Moreover, you probably don't want to check for equality. You should replace your condition with:
np.allclose(A.dot(eig_vec[:,col]), eig_val[col] * eig_vec[:,col])
Answered By - Martin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.