forward, backward and central differences

hey please i was trying to differentiate this function: y(x)=e^(-x)*sin(3x), using forward, backward and central differences using 101 points from x=0 to x=4. and plot the estimates and the actual function derivatives. here is my code:
f = @(x) exp(-x)*sin(3*x); %actual derivative of function fprime = @(x) -exp(-x)*sin(3*x)+ 3*exp(-x)*cos(3*x);
%step size:
h=0.04;
%forward difference dfdx_forward = (f(2+h)-f(2))/h Error_forward = fprime(2)-dfdx_forward %error
%bacward difference
dfdx_backward = (f(2)-f(2-h))/h
Error_backward = fprime(2)-dfdx_backward %error
%central difference
dfdx_central = (f(2+h)-f(2-h))/(2*h)
Error_central = fprime(2)-dfdx_central %error
please let me know if this is right and where i made my mistakes

 採用された回答

Mohammad Abouali
Mohammad Abouali 2015 年 4 月 27 日

18 投票

Fun = @(x) exp(-x).*sin(3*x);
dFun = @(x) -exp(-x).*sin(3*x)+ 3*exp(-x).*cos(3*x);
x=linspace(0,4,101);
F=Fun(x);
h=x(2)-x(1);
xCentral=x(2:end-1);
dFCenteral=(F(3:end)-F(1:end-2))/(2*h);
xForward=x(1:end-1);
dFForward=(F(2:end)-F(1:end-1))/h;
xBackward=x(2:end);
dFBackward=(F(2:end)-F(1:end-1))/h;
plot(x,dFun(x));
hold on
plot(xCentral,dFCenteral,'r')
plot(xForward,dFForward,'k');
plot(xBackward,dFBackward,'g');
legend('Analytic','Central','Forward','Backward')

8 件のコメント

lomesh rajyaguru
lomesh rajyaguru 2018 年 6 月 14 日
good
Mike Frank
Mike Frank 2019 年 10 月 24 日
Thank you for this answer. It was super helpful.
isamh
isamh 2020 年 2 月 5 日
for the central difference
dFCenteral=(F(3:end)-F(1:end-2))/(2*h);
what does the 3 in (F(3:end) and what does the 2 in F(1:end-2) do?
Kai Lu
Kai Lu 2021 年 3 月 16 日
@isamh F(3) is the third element. Meanwhile, the F(end-2) is the 2nd last element.
Javan See
Javan See 2021 年 9 月 28 日
編集済み: Javan See 2021 年 9 月 28 日
if the code for forward and backward is the same wont they have the same set of answers?
John D'Errico
John D'Errico 2021 年 9 月 28 日
@Javan See - good question. But in fact, the result is subtly different. You can see they are plotted versus xForward and XBackward. And THOSE x vectors are in fact different, offset by the stride h. The point being that one of these derivative estimates at the point x, will be a function of the value at f(x) and f(x+h). But the other estimate at that point will be determined by f(x-h) and f(x).
The difference will be tiny most of the time, and will only be seen when you look carefully. But it is a difference.
Tan Bing Jiat
Tan Bing Jiat 2022 年 4 月 13 日
for the xcentral
xCentral=x(2:end-1);
what does x(2:end-1); means?
Stephen Owino Omondi
Stephen Owino Omondi 2022 年 10 月 1 日
Good work Mr.Abouali, inline with the numerical formulation

サインインしてコメントする。

その他の回答 (1 件)

カテゴリ

ヘルプ センター および File ExchangeMATLAB についてさらに検索

質問済み:

2015 年 4 月 27 日

回答済み:

2025 年 3 月 21 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by