Jeremy Bos
MA4635
Final
5.3)9)a)

Use the Galerkin method to find the approximate solution for Ex 15 
u(x)=x + (∫_(-1)^1) xtu(
              t) dt in terms of 2 sets of independent functions.

Remove["Global`*"]

n = 3;
ul = 1;
ll = -1;
Array[ph, {1, n}];
cvar = Table[(Subscript[c, i]), {i, n}];
et = Table[0, {n}] ;
gallerr = Table[0, {n}] ;
lerr = Table[0, {n}] ;
as = Table[0, {n}] ;

f[x_] = x;

Create the ϕ's

Clear[k];  k = 0;
ph[1, x_] := 1;
For[k = 3, k ≤ n, 
      k += 2, 
ph[k, x] = 
        Cos[((((k - 1))/2))*x]
]

Clear[k]; k = 0;
For[k = 2, k ≤ n - 1, 
      k += 2, 
ph[k, x] = 
        Sin[((k/2))*x]
]

Create (Subscript[S, N])

sn[x_] = (∑_(i = 1)^n)((Subscript[c, i])*ph[i, x])

Find the error

eu[x_] = 
      sn[x] - ((∫_(-1)^1) x*t*
              sn[t] \[DifferentialD]t)

Implementation of the Galerkin Method

Clear[k]
For[k = 1, 
      k ≤ 
        n, k++, 
gallerr[[k]] = (∫_ll^ul)(ph[k, x]*eu[x]) \[DifferentialD]x; 
      Print[gallerr[[k]]]
]

Clear[k]
For[k = 1, 
      k ≤ 
        n, k++, 
lerr[[k]] = (∫_ll^ul)(ph[k, x]*f[x]) \[DifferentialD]x; 
      Print[lerr[[k]]]
]

Solve for the (Subscript[c, i])' s

soln = Solve[gallerr == lerr, cvar]

Clear[i, k]
For[k = 1, 
      k ≤ n, k++, 
as[[k]] = 
        N[(Subscript[c, k]) /. soln]; Print[as[[k]]];
]

Approximate the solution

fas[x_] = (∑_(i = 1)^n) as[[i]]*ph[i, x]

Plot[{fas[x], 3*x}, {x, -2, 2}, 
      PlotStyle -> {{Hue[1]}, {Hue[0.55]}}]

Clear[k]
delta = ((ul - ll)/(n - 1));
For[k = 1, 
      k ≤ n, k++, 
Print["Actual  ", 
        N[3*(ll + ((k - 1)*
                    delta))], " ", "     Approximate ", 
        N[fas[ll + ((k - 1)*delta)]]]
]

Find the Least Square Error:
  The LSE can be found by squaring the difference between the exact and approximated solutions

LSE = (∫_ll^ul)(((3  x - 
                  fas[x]))^2) \[DifferentialD]x

By contrast the LSE for the collocation method was 0.423642. Obviously the Galerking method provides a better approximation for N=3.