## Lecture 6, we see the Neumann series method.
## Recall our linear system to find the expected length of that
# simple "random walk" on the integers.
using LinearAlgebra
A = Matrix(SymTridiagonal(ones(11), -0.5*ones(10)))
##
A[1,2] = 0
A[end,end-1] = 0
b = [0;ones(9);0]
##
xjulia = A\b
##
""" Solve a linear system of equations \$A x = b\$
using a method based
on the Neumann series for the inverse. This will converge
if the spectral radius of \$(I - A)\$ is less than 1.
* `A`: The square, non-singular matrix to solve
* `b`: The right hand size
"""
function solve_linsys(A::Matrix,b::Vector; niter=0)
n = size(A,1)
@assert(n == size(A,2), "The matrix is not square")
if niter <= 0
niter = 10*size(A,1)
end
x = copy(b) # make a copy of the right hand side
r = b - A*x # compute the residual
iter = 0
while norm(r) >= n*eps(1.0) && iter <= niter
x .+= r # this works in place!
iter += 1
r = b - A*x
end
@show iter
return x
end
x = solve_linsys(A,b)
##
norm(b-A*x)
##
x = solve_linsys(A,b; niter=10000)
##
norm(b-A*x)