Spectral Differentiation using FFT

Converted Trefethen’s program p4.m from Matlab to Mathematica using claude.ai (partially modified)

(* Setup common parameters *)
n=24;
h=2*Pi/n;
x=N[Table[h*i,{i,1,n}]];

(* Define auxiliary plotting function *)
createPlot[data_,title_,yRange_]:=ListPlot[Transpose[{x,data}],PlotStyle->{Blue,PointSize[0.03]},Joined->True,Mesh->All,PlotRange->{{0,2*Pi},yRange},GridLines->Automatic,Frame->True,FrameLabel->{{"",""},{"x",title}},ImageSize->Medium]

(* Part 1: Differentiation of a hat function *)
v=Table[Max[0,1-Abs[x[[i]]-Pi]/2],{i,1,n}];
vHat=Fourier[v,FourierParameters->{1,-1}];

(* Create k vector for spectral differentiation and multiply the Fourier image by i*k *)
k=Join[Table[i,{i,0,n/2-1}],{0},Table[i-n,{i,n/2+1,n-1}]];
wHat=I*k*vHat;

(* Compute spectral derivative *)
w=Re[InverseFourier[wHat,FourierParameters->{1,-1}]];

(* Create plots for hat function *)
hatPlot=createPlot[v,"hat function",{-0.5,1.5}];
hatDerivPlot=createPlot[w,"spectral derivative",{-1,1}];

(* Part 2: Differentiation of exp(sin(x)) *)
v2=Table[Exp[Sin[x[[i]]]],{i,1,n}];
v2Prime=Table[Cos[x[[i]]]*Exp[Sin[x[[i]]]],{i,1,n}];

(* Compute Fourier transform *)
v2Hat=Fourier[v2,FourierParameters->{1,-1}];
w2Hat=I*k*v2Hat;

(* Compute spectral derivative *)
w2=Re[InverseFourier[w2Hat,FourierParameters->{1,-1}]];

(* Create plots for exp(sin(x)) *)
expSinPlot=createPlot[v2,"exp(sin(x))",{0,3}];
expSinDerivPlot=createPlot[w2,"spectral derivative",{-2,2}];

(* Display all plots together *)
Grid[{{hatPlot,hatDerivPlot},{expSinPlot,expSinDerivPlot}}]

(* Calculate error *)
error=Max[Abs[w2-v2Prime]];
Print["Error of the spectral derivative for the smooth function exp(sin(x)) is ",error]