from __future__ import division
import numpy as np
import matplotlib.pyplot as pt
import scipy.sparse as sps
We'll solve
\(u''+1000(1+x^2)u=0\) on \((-1,1)\)
with \(u(-1)=3\) and \(u(1)=-3\).
n = 500
mesh = np.linspace(-1, 1, n)
h = mesh[1] - mesh[0]
A = sps.diags(
[1,-2,1],
offsets=[-1,0,1],
shape=(n, n))
if n < 10:
print A.todense()
Need to restrict to middle rows!
second_deriv = ...
if n < 10:
print second_deriv.todense()
(Edit this cell for solution)
factor = sps.diags(
[1000*(1 + mesh[1:]**2)],
offsets=[1],
shape=(n-2, n))
if n < 10:
print mesh[1:-1]
print
print factor.todense()
A_int = second_deriv+factor
if n < 10:
print A_int.todense()
A = sps.vstack([
sps.coo_matrix(([1], ([0],[0])), shape=(1, n)),
A_int,
sps.coo_matrix(([1], ([0],[n-1])), shape=(1, n)),
])
A = sps.csr_matrix(A)
if n < 10:
print A.todense()
rhs = np.zeros(n)
...
(Edit this cell for solution.)
import scipy.sparse.linalg as sla
sol = sla.spsolve(A, rhs)
pt.plot(mesh, sol)