# Mean error of finite differences derivative

I wrote a module that computes the 4-th order finite difference derivative of a function at $$N$$ equidistant points of an interval and the difference between the exact and numerical value at those points, and tested it on the function $$f(x)=e^{-x^2}$$. I would then like to show that the mean error $$= \frac{1}{N} \sum_{i=0}^{N} |e_i|$$ (where $$e_i$$ is the difference at the $$i$$-th point of the interval) decreases proportionally with $$N^{-4}$$, by experimenting with different values for $$N$$. I chose $$N=\{2^4,2^5,...,2^{15}\}$$, but the computation is very slow and the listplot does not even show that the mean error decreases proportionally with $$N^{-4}$$, why does all that happen? Thanks in advance!

der4[gridpoints_,values_,order_]:= Module[{x=gridpoints, y=values, k=order},
de=NDSolveFiniteDifferenceDerivative[Derivative[k],N[x],"DifferenceOrder"->4]@"DifferentiationMatrix"//Normal; de.N[y]]
number=31;
f[x_]:=Exp[-8*x^2];
grid=Subdivide[-1, 1, number];
val=f[grid];
approx=der4[grid,val,1]
difference=approx-f'[grid];
ListPlot[difference, PlotLabel->"Difference between numerical and analytical solution for f(x)", AxesLabel->{x, "Difference"}]

Num=ConstantArray[0.,12];
Do[Num[[n]]=2^(n+3), {n, 1, 12}];
err=ConstantArray[0.,12];
Do[grid1=Subdivide[-1, 1, Num[[n]]]; err[[n]]=(1/Num[[n]])*Total[Abs[der4[grid1,f[grid1],1]-f'[grid1]]], {n, 1, 12}];
ListPlot[Transpose[{Num^(-4), err}], AxesLabel->{"N^(-4)","Mean error"}, PlotLabel->"Mean error decrease"]

• Welcome to Mathematica.SE! I hope you will become a regular contributor. To get started, 1) take the introductory tour now, 2) when you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge, 3) remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign, and 4) give help too, by answering questions in your areas of expertise. Nov 20, 2021 at 20:43
• To speed it up, get rid of the Normal. The SparseArray representation of your very large differentiation matrix is your friend. Otherwise for n = 11, 12 you spend most of the time swapping (my memory usage said 15+GB). If I use ListLogLogPlot`, I see the decrease, up to a point that's probably expected. Nov 20, 2021 at 21:40
• @MichaelE2 Thank you! Nov 20, 2021 at 23:11