import numpy as np
import matplotlib.pyplot as plt
# Draw the circles from the matrix
def GershgorinCircles(B):
'''
GershgorinCircles(B)
Create a plot of the Gershgorin circles from the rows
of the square matrix B. It also plots the eigenvalues.
'''
c = []
for k,r in enumerate(B):
ctr = r[k]
radius = np.sum(np.abs(r)) - np.abs(ctr)
print('Centre = '+str(ctr)+' , Radius = ',str(radius))
c.append( plt.Circle((np.real(ctr), np.imag(ctr)), radius=radius, fill=True, alpha=0.25) )
# Create the plot, and add the eigenvalues on top
fig = plt.figure(figsize=(6,6))
ax = plt.gcf().gca()
ax.set_xlim(left=-4, right=4); plt.xlabel('Real')
ax.set_ylim(bottom=-4, top=4); plt.ylabel('Imag')
ax.grid('on')
if True:
v = np.linalg.eig(B)[0]
for cc in c:
plt.gcf().gca().add_artist(cc)
for vv in v:
plt.plot([np.real(vv)], [np.imag(vv)], 'bo')
rr = np.random.randint(0, 500)
np.random.seed(seed=rr)
# Random matrix
B = np.random.normal(size=(3,3))
B = np.round(B, decimals=1)
v = np.linalg.eig(B)[0]
print(B)
for vv in v:
print(np.round(vv, decimals=3))
[[-1.8 -0.4 0.4] [-0.3 0.1 0. ] [ 0.9 0.9 0.5]] -2.02 0.26 0.56
B = np.array([[1,0.5,0.5],[0.5,2,1],[1,1,-2.]])
GershgorinCircles(B)
Centre = -1.8 , Radius = 0.8 Centre = 0.1 , Radius = 0.30000000000000004 Centre = 0.5 , Radius = 1.7999999999999998
# Try a different random matrix
B = np.random.normal(size=(5,5))
B = np.round(B, decimals=1)
v = np.linalg.eig(B)[0]
print(B)
for vv in v:
print(np.round(vv, decimals=3))
GershgorinCircles(B)
[[-0.7 0.6 -1.6 0. -0.4] [ 0.7 0.9 0. 0.4 0.2] [ 0.8 1.6 0.3 -0.7 1.3] [-0.2 -0.4 0.8 0.4 -0.1] [-0.7 0.9 0.6 -0.3 0.3]] (-0.615+0.575j) (-0.615-0.575j) (0.959+0j) (0.735+0.734j) (0.735-0.734j) Centre = -0.7 , Radius = 2.5999999999999996 Centre = 0.9 , Radius = 1.3000000000000003 Centre = 0.3 , Radius = 4.4 Centre = 0.4 , Radius = 1.5000000000000004 Centre = 0.3 , Radius = 2.5
n = 7
B = (np.random.random(size=(n,n)) - 0.5)/2.
B += np.eye(n) * np.diag(np.random.choice([-1,1], size=n))
print(np.round(B, decimals=2))
print(np.sum(np.abs(B), axis=1))
GershgorinCircles(B);
[[ 1.1 0. 0.11 0.11 -0.16 0.06 0.13] [-0.14 -0.76 0.11 0.03 -0.03 -0.22 0.1 ] [ 0.13 0.15 1.13 -0.01 0.14 -0.04 0.05] [ 0.08 0.11 -0.18 1.17 -0.01 0.24 -0.04] [ 0.16 -0.2 0.21 0.1 -1.23 -0.02 0.08] [ 0.21 -0.24 0.24 0.06 0.01 -0.96 0.12] [-0.01 0.03 0.18 0.24 -0. 0.06 -0.94]] [1.66711384 1.38293729 1.64428072 1.82974381 1.99643509 1.83471717 1.46712431] Centre = 1.0982638254305386 , Radius = 0.5688500149794333 Centre = -0.7583377820442232 , Radius = 0.6245995104047173 Centre = 1.1273585437401192 , Radius = 0.5169221763688268 Centre = 1.1689815008061848 , Radius = 0.6607623107040137 Centre = -1.2283474742850158 , Radius = 0.7680876146085474 Centre = -0.9608743757373852 , Radius = 0.8738427957964658 Centre = -0.9441343433957126 , Radius = 0.5229899635895816