Off[General::spell1];
Clear[TriMat,aa,dd,cc,bb,n];
TridiagM[aa_,dd_,cc_,bb_,n_] :=
  Module[{a0,b0,c0,d0,i,t},
    a0=aa; 
    b0=bb;
    c0=cc;
    d0=dd;
    Clear[x0];
    x0 = Table[0,{n}];
    For[i=2,i<=n,i++,
      Module[{},
        t = a0[[i-1]]/d0[[i-1]];
        d0[[i]] = d0[[i]] - t c0[[i-1]];
        b0[[i]] = b0[[i]] - t b0[[i-1]] ]; ];
    x0[[n]] =  b0[[n]]/d0[[n]];
    For[i=n-1,1<=i,i--,
       x0[[i]] = (b0[[i]] - c0[[i]] x0[[i+1]])/
                  d0[[i]] ];
    Return[x0] ];

Clear[CrankNicolson,a,b,g, n, k, M,u]; 
CrankNicolson[a0_,b0_,g0_,n_,k_,M_] :=
Module[{a,b,g,h,s,i,j,,X,Aa,Bb,Cc,Dd},  
  Set@@{a[t_],a0};
  Set@@{b[t_],b0};
  Set@@{g[x_],g0}; 
  h = (1 / n)//N;
  s = (k / h^2) //N;
 Aa = Table[-s,{n-2}];    
 Cc = Table[-s,{n-2}];
 Dd = Table[2+2s, {n-1} ]; 
 Bb = Table[0,{n }];
u = Table[0,{n+1},{M}];
  For[i=1,i<=n+1 ,i++,
      u[[i,1]] = g[(i-1)*h] //N ];
  For[j=1,j<=M,j++,
      u[[1,j]] = a[j*k] //N ;   
      u[[n+1,j]] = b[j*k] //N ];
 X = Table[0,{n}];
  For[j=2,j<=M,j++,
       Bb[[1]]=a[(j-1)*k]; 
       Bb[[n]]=b[(j-1)*k];
    For[i=2,i<=n-1,i++,
       Bb[[i]] = s*u[[i-1,j-1]] + (2-2s)*u[[i,j-1]]+
           s*u[[i+1,j-1]] //N ]; 
 X = TridiagM[Aa,Dd,Cc,Bb,n-1];
  For[i=2,i<=n,i++,
        u[[i,j]] = X[[i -1]] //N]; ]; ];  
On[General::spell1]

Clear[g,t,x]; 
g[x_]:= 4*x -4*x^2; 
a[t_]:=0; 
b[t_]:=0;

CrankNicolson[a[t],b[t],g[x], 5, 0.02, 20] ;

ListPlot3D[u,  AxesLabel->{"t","x","u"},   
ViewPoint->{4,2,3}]

CrankNicolson[a[t],b[t],g[x], 5, 0.06, 15];

ListPlot3D[u,  AxesLabel->{"t","x","u"},   
ViewPoint->{4,2,3}]

Clear[g,t,x];
g[x_]:= Sin[Pi*x];
a[t_]:=0;
b[t_]:=0;

CrankNicolson[a[t],b[t],g[x], 50, 0.05, 20];

ListPlot3D[u,  AxesLabel->{"t","x","u"},   
ViewPoint->{1,2,1}]

uu[x_,t_]:=Exp[- Pi^2 t] * Sin[Pi *x];

Error = Max[Abs[ Table[u[[i,j]]-  
  uu[0.02*(i-1),0.05*(j-1)] //N, {i,1,51},{j,1,20}]]]

D[uu[x,t],{x,4}]

D[uu[x,t],{t,2}]

Pi^4 / 12 + 125*Pi^4 /2 //N

CrankNicolson[a[t],b[t],g[x], 10, 0.1, 10];

ListPlot3D[u,  AxesLabel->{"t","x","u"},   
ViewPoint->{1,2,1}]

Error = Max[Abs[ Table[u[[i,j]]- 
    uu[0.1*(i-1),0.1*(j-1)] //N, {i,1,11},{j,1,10}]]]