# Truncation error plot with weird issue

I have a function f(x) = sin(x)/x^3 whose first derivative I am trying to estimate using 1st, 2nd and 4th order Finite Difference schemes. I tried to plot the truncation error in MATLAB and I found myself with increasing error with smaller step size. I am not sure where I am wrong. Attached is my code snippet.

syms y
dx = linspace(10^(-5), 10^(-0));
f = @(x) sin(x)/x^3;
x = 4;

df1 = (f(x+1)-f(x))./dx;
df2 = (f(x+1)-f(x-1))./(2.*dx);
df4 = (f(x-2)-8*f(x-1)+8*f(x+1)-f(x+2))./(12.*dx);

exact = cos(x)/x^3 - (3*sin(x))/x^4;

for i=1:length(dx)
error1(i) = abs(df1(i)-exact)
error2(i) = abs(df2(i)-exact)
error4(i) = abs(df4(i)-exact)
end

figure
loglog(dx,error1,'r','linewidth',2)
hold on
loglog(dx,error2,'b','linewidth',2)
loglog(dx,error4,'k','linewidth',2) • Found the problem. I forgot to multiply by dx inside the difference. – Yukti Kathuria Feb 17 '20 at 23:13
• Nice work! Probably worth posting the correct code and accepting your own answer. Otherwise the site will just continue to auto-bump your question, in an effort to attract answers. – rchilton1980 Feb 18 '20 at 3:04

## 1 Answer

The thing missing in the code was taking into account a factor of dx when calculating the function values in the finite difference schemes, which was causing them to become larger as they got divided by smaller step sizes in the bottom and blew up in the numerator.

So the correct code will look like:

df1 = (f(x+1*dx)-f(x))./dx;
df2 = (f(x+1*dx)-f(x-1*dx))./(2.*dx);
df4 = (f(x-2*dx)-8*f(x-1*dx)+8*f(x+1*dx)-f(x+2*dx))./(12.*dx);

• You can accept your answer. – nicoguaro Feb 22 '20 at 13:21