Discretization Method for BVP

In this notebook, we demonstrate using the discretization or finite-element method to solve the boundary value problem

	x''(t) = u(t) + v(t) x(t) + w(t) x'(t)
	
with boundary conditions x(a) = x0, x(b) = x1 and a varying number of steps. This is blissfully short in Mathematica:

FEMSolve[u_,v_,w_,a_,b_,x0_,x1_,n_] := 

Module[{A,B,h,ti,ui,vi,wi,i,X},

h = (b-a)/n;
ti = Table[a + h*i,{i,1,n-1}];

ui = Table[u[ti[[i]]],{i,1,n-1}];
vi = Table[v[ti[[i]]],{i,1,n-1}];
wi = Table[w[ti[[i]]],{i,1,n-1}];

B = -h^2 ui;
B[[1]]       += (1 + (h/2)w[a])*x0;
B[[n-1]] += -((h/2) w[b] - 1)*x1;

A = SparseArray[{Band[{1,1}]->(2 + h^2 vi),Band[{1,2}] -> ((h/2)*wi[[1;;n-2]] - 1),
Band[{2,1}] -> (-(h/2)*wi[[2;;n-1]] - 1)},{n-1,n-1}];

X = LinearSolve[A,B];

AppendTo[X,x1];
PrependTo[X,x0];

PrependTo[ti,a];
AppendTo[ti,b];

Transpose[{ti,X}]

];

u[t_] := Exp[t] - 3 Sin[t];
v[t_] := -1;
w[t_] := 1;

test = FEMSolve[u,v,w,1.0,2.0,1.09737491,8.63749661,100]

Manipulate[Show[ListLinePlot[FEMSolve[u,v,w,1.0,2.0,1.09737491,8.63749661,n],Filling->Axis,PlotMarkers->Automatic,AxesOrigin->{1,0}],Plot[Exp[t] - 3Cos[t],{t,1,2}],AxesOrigin->{1,0},PlotRange->{{1,2},{0,9}},
AxesLabel->{Style["t",Medium,FontFamily->"Helvetica",Bold],Style["x",Medium,FontFamily->"Helvetica",Bold]},PlotLabel->Style["FEM Solution vs Exact Solution for x''[t] = Exp[t] - 3 Sin[t] + x[t] - x'[t]",Medium,FontFamily->"Helvetica",Bold],ImageMargins->Medium,ImageSize->600],
{n,3,1000,1}]

FEMError[n_] := Module[ {X,Exact},

Exact[t_] := Exp[t] - 3 Cos[t];
X = FEMSolve[u,v,w,1.0,2.0,1.09737491,8.63749661,n];

Max[Abs[Table[X[[i,2]] - Exact[X[[i,1]]],{i,1,Length[X]}]]]

];

Digits[a_,b_] := N[Abs[Log[10,Abs[a -b]]]];
FEMErrorData = Table[{n,Digits[FEMError[n],0]},{n,10,1000,10}];

ListLinePlot[FEMErrorData,Filling->Axis,PlotMarkers->Automatic,AxesLabel->{Style["n",Medium,FontFamily->"Helvetica",Bold],Style["Digits",Medium,FontFamily->"Helvetica",Bold]},PlotLabel->Style["Accurate digits of FEM Solution for x''[t] = Exp[t] - 3 Sin[t] + x[t] - x'[t] at t_i",Medium,FontFamily->"Helvetica",Bold]]