The following illustrates how to use the numpy
and scipy.linalg
modules to work with matricies by solving problem A.8 from Introduction to Quantum Mechanics, 2nd Edition by David Griffiths and another example eigenvalue problem.
import numpy as np
import scipy.linalg as la
Given the matricies $\mathbf{A}$ and $\mathbf{B}$ compute the quantities specified in parts (a) through (i) below.
Define matrix $\mathbf{A}$ and $\mathbf{B}$.
A = np.array([[-1,1,1j],
[2,0,3],
[2j,-2j,2]])
B = np.array([[2,0,-1j],
[0,1,0],
[1j,3,2]])
print('A = ',A)
print('B = ',B)
C = A+B
print(C)
The NumPy uses the @
symbol for the matrix multiplication operator.
A@B
A@B-B@A
A.T
A.conjugate()
A.conjugate().T
np.trace(B)
la.det(B)
Check that $\mathbf{BB}^{-1} = \mathbf{I}$. Does $\mathbf{A}$ have an inverse?
Binv = la.inv(B)
print(Binv)
BBI = Binv@B
print(BBI)
This confirms that $\mathbf{BB}^{-1} = \mathbf{I}$. The very small numbers in the off-diagonal elements are due to rounding errors.
If $\mathrm{det}(\mathbf{A}) \neq 0$, then $\mathbf{A}$ has an inverse.
la.det(A)
$\mathrm{det}(\mathbf{A}) = 0$ so $\mathbf{A}$ does not have an inverse.
Find the eigenvalues and eigenvectors of the matrix $\mathbf{M}$ below.
M = np.array([[1,0,1],
[0,1,0],
[1,0,1]])
The la.eig()
function takes a square matrix as its argument and returns two arrays. One is an a one-dimensional array that contains all the eigenvalues. The second array is a two-dimensional array with each column of the array being one of the eigenvectors. The code below illustrates how to extract the eigenvalues and eigenvectors from the output of la.eig()
.
e_val,e_vec = la.eig(M)
In this case e_val
is an array with three elements—one element for each eigenvalue.
print('The eigenvalues are:',e_val)
As expected for this matrix, all of the eigenvalues are real. The imaginary part of each eigenvalue is zero.
Now we can extract the eigenvector for each eigenvalue and print the results.
for idx in range(len(e_val)):
value = e_val[idx]
vector = e_vec[:,idx]
print(f'For the eigenvalue {value}, the eigenvector is {vector}.')