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 $<e>= \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=NDSolve`FiniteDifferenceDerivative[Derivative[k],N[x],"DifferenceOrder"->4]@"DifferentiationMatrix"//Normal; de.N[y]]
grid=Subdivide[-1, 1, number];
ListPlot[difference, PlotLabel->"Difference between numerical and analytical solution for f(x)", AxesLabel->{x, "Difference"}]

Do[Num[[n]]=2^(n+3), {n, 1, 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"]
  • 1
    $\begingroup$ 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. $\endgroup$
    – bbgodfrey
    Nov 20, 2021 at 20:43
  • 2
    $\begingroup$ 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. $\endgroup$
    – Michael E2
    Nov 20, 2021 at 21:40
  • $\begingroup$ @MichaelE2 Thank you! $\endgroup$
    – JBuck
    Nov 20, 2021 at 23:11


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.