Eigenvalues

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Eigenvalues and Eigenvectors

[1]: import numpy as np


import matplotlib.pyplot as plt

plt.style.use(”seaborn-v0_8-poster”)

def plot_vect(x, b, xlim, ylim):


”””
function to plot two vectors,
x - the original vector
b - the transformed vector
xlim - the limit for x
ylim - the limit for y
”””

plt.figure(figsize = (6, 4))


plt.quiver(0,0,x[0],x[1],\
color=”k”,angles=”xy”,\
scale_units=”xy”,scale=1,\
label=”Original vector”)
plt.quiver(0,0,b[0],b[1],\
color=”g”,angles=”xy”,\
scale_units=”xy”,scale=1,\
label =”Transformed vector”)
plt.xlim(xlim)
plt.ylim(ylim)
plt.xlabel(”X”)
plt.ylabel(”Y”)
plt.legend()
plt.show()

[2]: A = np.array([[2, 0],[0, 1]])


x = np.array([[1],[1]])
b = np.dot(A, x)
plot_vect(x,b,(0,3),(0,2))

1
[3]: x = np.array([[1], [0]])
b = np.dot(A, x)
plot_vect(x,b,(0,3),(-0.5,0.5))

2
[4]: # Power Method

def normalize(x):
fac = abs(x).max()
x_n = x / x.max()
return fac, x_n

[5]: x = np.array([0.4,1])
x.max()

[5]: 1.0

[6]: from numpy.linalg import inv

x = np.array([1, 1])
a = np.array([[0, 2],
[2, 3]])

a_inv = inv(a)

for i in range(100):
x = np.dot(a_inv, x)
lambda_1, x = normalize(x)

print(”Eigenvalue:”, lambda_1)
print(”Eigenvector:”, x)

Eigenvalue: 2.0
Eigenvector: [ 1. -0.5]

[7]: from numpy.linalg import inv

x = np.array([1, 1])
a = np.array([[0, 2],
[2, 3]])

a_inv = inv(a)

for i in range(100):
x = np.dot(a_inv, x)
lambda_1, x = normalize(x)

print(”Eigenvalue:”, lambda_1)
print(”Eigenvector:”, x)

Eigenvalue: 2.0
Eigenvector: [ 1. -0.5]

3
[8]: # QR method

from numpy.linalg import qr

a = np.array([[0, 2],
[2, 3]])
q, r = qr(a)
print(”Q:”, q)
print(”R:”, r)

b = np.dot(q,r)
print(”QR:”, b)
print(b==a)

Q: [[ 0. -1.]
[-1. 0.]]
R: [[-2. -3.]
[ 0. -2.]]
QR: [[0. 2.]
[2. 3.]]
[[ True True]
[ True True]]

[9]: # QR method

a = np.array([[0, 2],
[2, 3]])
p = [1, 5, 10, 20,100]

for i in range(100):
q, r = qr(a)
a = np.dot(r, q)

if i+1 in p:
print(f”\nIteration {i+1}:”)
print(a)

Iteration 1:
[[3. 2.]
[2. 0.]]

Iteration 5:
[[ 3.99998093 0.00976559]
[ 0.00976559 -0.99998093]]

Iteration 10:
[[ 4.00000000e+00 9.53674316e-06]

4
[ 9.53674316e-06 -1.00000000e+00]]

Iteration 20:
[[ 4.00000000e+00 9.09482285e-12]
[ 9.09494702e-12 -1.00000000e+00]]

Iteration 100:
[[ 4.00000000e+00 -1.24166995e-16]
[ 6.22301528e-60 -1.00000000e+00]]

[10]: # eig() in NumPy

import numpy as np
from numpy.linalg import eig

a = np.array([[0,2],[2,3]])

w,v = eig(a)

print(f”Eigenvalues: {w}”)
print(f”Eigenvectors: {v}”)

Eigenvalues: [-1. 4.]


Eigenvectors: [[-0.89442719 -0.4472136 ]
[ 0.4472136 -0.89442719]]

[ ]:

You might also like