How to find Eigen value and Eigen vector using Python
These are the concepts available in Linear algebra. It has the following definitions.
Eigenvalue(λ): It is a scalar value.It shows about
the eigen vector stretch and compress in terms of linear transformation.
Eigenvector(v): It is a vector value.It is a non-zero vector
which changes the scale alone.
The formula for square matrix A is given below.
Av=λv
Where A represents matrix. ‘v’ denotes eigenvector. ‘λ’ is
for eigenvalue.
Let us implement the eigen value and eigen vector in python.
This program imports numpy package with its object np.
A square matrix is created with elements.
Eigenvalues and eigenvectors variables are declared.
There is a function ‘linalg.eig(matrix)’ which generate the eigenvalues
and eigenvectors.
Python Program:
import numpy as np
# Declare a square matrix
A = np.array([[5, 3, 2],
[1,-1,
4],
[2, 6,
8]])
# Generate eigenvalues and eigenvectors
eigenvalues, eigenvectors = np.linalg.eig(A)
print("Matrix A:\n", A)
print("\nEigenvalues:\n", eigenvalues)
print("\nEigenvectors:\n", eigenvectors)
Output:
Matrix A:
[[ 5 3 2]
[ 1 -1 4]
[ 2 6 8]]
Eigenvalues:
[11.21110255+0.j 4.
+0.j -3.21110255+0.j]
Eigenvectors:
[[ 0.4247359
+0.j 0.93638218+0.j 0.21532584+0.j]
[ 0.31304487+0.j
-0.08512565+0.j -0.87645531+0.j]
[ 0.84947179+0.j
-0.34050261+0.j 0.43065168+0.j]]
Let us code create another python code to verify A * v ≈ λ *
v:
import numpy as np1
# Square matrix A is created
A = np1.array([[4, 5],
[3, 8]])
# Generation of eigenvalues and eigenvectors
eigenvalues, eigenvectors = np1.linalg.eig(A)
print("Matrix A:\n", A)
print("\nEigenvalues:\n", eigenvalues)
print("\nEigenvectors (columns):\n", eigenvectors)
# Verification code: A * v ≈ λ * v
for i in range(len(eigenvalues)):
v = eigenvectors[:,
i] # i-th eigenvector
λ = eigenvalues[i] # i-th eigenvalue
Av = A @ v # Matrix-vector multiplication
λv = λ * v
print(f"\nVerification
for eigenvalue {λ:.2f}:")
print("A @ v
=", Av)
print("λ * v
=", λv)
print("Difference
=", Av - λv)
Output:
Matrix A:
[[4 5]
[3 8]]
[ 1.64110106+0.j
10.35889894+0.j]
[[-0.90440309+0.j
-0.61810602+0.j]
[ 0.4266791 +0.j
-0.78609474+0.j]]
Verification for eigenvalue 1.64+0.00j:
A @ v = [-1.48421686+0.j
0.70022352+0.j]
λ * v = [-1.48421686+0.j
0.70022352+0.j]
Difference = [4.44089210e-16+0.j 1.11022302e-16+0.j]
Verification for eigenvalue 10.36+0.00j:
A @ v = [-6.4028978 +0.j -8.14307602+0.j]
λ * v = [-6.4028978 +0.j -8.14307602+0.j]
Difference = [-8.8817842e-16+0.j 0.0000000e+00+0.j]
Thus the python code to generate eigenvalue and eigenvector
and verification was done successfully. Hope, this code is useful to you. Keep
Coding!!!
Comments
Post a Comment