In [1]:
import numpy as np
import scipy as sp
import scipy.sparse as sparse
import scipy.sparse.linalg as sla
import matplotlib.pyplot as plt
%matplotlib inline
In [3]:
n = 100
A = sparse.diags([-1, 2, -1], [-1, 0, 1], shape=(n,n), format='csr')
b = np.zeros((n,))
In [4]:
lambdamin, v = sla.eigs(A, 1, which='SM', maxiter=10000)
lambdamax, v = sla.eigs(A, 1, which='LM', maxiter=10000)
print(lambdamin, lambdamax)
[ 0.00096744+0.j] [ 3.99903256+0.j]
In [5]:
err = []
res = []
alpha = 2 / (lambdamin.real + lambdamax.real)
print(alpha)
#alpha = 0.45
x = np.random.rand(n)
for i in range(100):
    x = x + alpha * (b - A*x)
    err.append(np.linalg.norm(x))
    res.append(np.linalg.norm(b-A*x))
[ 0.5]
In [6]:
plt.semilogy(res)
Out[6]:
[<matplotlib.lines.Line2D at 0x10e957940>]
In [7]:
print((lambdamin.real - lambdamax.real)/(lambdamin.real + lambdamax.real))
[-0.99951628]
In [89]:
err = np.array(err)
err[1:] / err[:-1]
Out[89]:
array([ 0.98102653,  0.98975526,  0.9931536 ,  0.99486413,  0.99586553,
        0.99651494,  0.99696803,  0.99730165,  0.99755746,  0.99775975,
        0.99792356,  0.99805876,  0.99817208,  0.9982683 ,  0.99835094,
        0.99842263,  0.99848539,  0.99854078,  0.99859004,  0.99863417,
        0.99867395,  0.99871002,  0.99874291,  0.99877305,  0.9988008 ,
        0.99882645,  0.99885026,  0.99887244,  0.99889315,  0.99891257,
        0.99893081,  0.99894799,  0.99896421,  0.99897955,  0.99899408,
        0.99900788,  0.999021  ,  0.9990335 ,  0.99904541,  0.99905678,
        0.99906765,  0.99907805,  0.99908802,  0.99909757,  0.99910673,
        0.99911554,  0.999124  ,  0.99913214,  0.99913997,  0.99914752,
        0.9991548 ,  0.99916181,  0.99916858,  0.99917512,  0.99918144,
        0.99918755,  0.99919345,  0.99919917,  0.9992047 ,  0.99921006,
        0.99921526,  0.99922029,  0.99922518,  0.99922992,  0.99923452,
        0.99923898,  0.99924332,  0.99924754,  0.99925164,  0.99925562,
        0.9992595 ,  0.99926328,  0.99926695,  0.99927053,  0.99927402,
        0.99927742,  0.99928073,  0.99928396,  0.99928712,  0.99929019,
        0.99929319,  0.99929613,  0.99929899,  0.99930179,  0.99930452,
        0.99930719,  0.9993098 ,  0.99931236,  0.99931486,  0.99931731,
        0.9993197 ,  0.99932204,  0.99932434,  0.99932659,  0.99932879,
        0.99933095,  0.99933307,  0.99933515,  0.99933718])
In [ ]: