0
$\begingroup$

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)

Truncation error as a function of step size

$\endgroup$
2
  • $\begingroup$ Found the problem. I forgot to multiply by dx inside the difference. $\endgroup$ – Yukti Kathuria Feb 17 '20 at 23:13
  • 1
    $\begingroup$ 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. $\endgroup$ – rchilton1980 Feb 18 '20 at 3:04
2
$\begingroup$

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);
$\endgroup$
1
  • 1
    $\begingroup$ You can accept your answer. $\endgroup$ – nicoguaro Feb 22 '20 at 13:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.