Backward and Central Difference

1 回表示 (過去 30 日間)
Anna Lin
Anna Lin 2021 年 6 月 11 日
コメント済み: Anna Lin 2021 年 6 月 12 日
Given that x =10 and delta_x = 0.4,
Is there a better way of writing this code?
x = 10;
delta_x = 0.4;
backward_difference = ((2*f(x)-5*f(x-dx)+4*f(x-2*dx)-f(x-3*dx))/dx^2);
central_difference = (-f(x+2*dx)+16*f(x+dx)-30*f(x)+16*f(x-dx)-f(x-2*dx))/(12*(dx^2));
  2 件のコメント
Joseph Cheng
Joseph Cheng 2021 年 6 月 11 日
編集済み: Joseph Cheng 2021 年 6 月 11 日
Have you already defined "f" as an anonymous function or symbolic function? Otherwise if "f" is an array you would be indexing "f" in a non-integer value
Anna Lin
Anna Lin 2021 年 6 月 11 日
Yes, I have already defined f as an anonymous function.
f=@(x) x.^3+sin(x)

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

採用された回答

J. Alex Lee
J. Alex Lee 2021 年 6 月 11 日
I guess the answer depends what you want to do with those finite difference approximations. If you want to use it in an algorithm to solve ODEs, your strategy won't work because you don't a priori have a functional form.
This would be a typical matrix math way (assuming your coefficients are correct, i won't check)
cb = [-1,4,-5,2];
cc = [-1,16,-30,16,-1]/12;
fun = @(x) x.^3+sin(x);
funp = @(x) 3*x.^2 + cos(x);
funpp = @(x) 6*x - sin(x);
dx = 0.5;
x0 = 10;
% create stencils on x to define discrete f
xb = x0 - (3:-1:0)'*dx;
xc = x0 + (-2:2)'*dx;
% generate discrete f
fb = fun(xb);
fc = fun(xc);
% execute finite differences
fbpp = cb*fb/dx^2
fbpp = 60.5508
fcpp = cc*fc/dx^2
fcpp = 60.5437
backward_difference = ((2*fun(x0)-5*fun(x0-dx)+4*fun(x0-2*dx)-fun(x0-3*dx))/dx^2)
backward_difference = 60.5508
central_difference = (-fun(x0+2*dx)+16*fun(x0+dx)-30*fun(x0)+16*fun(x0-dx)-fun(x0-2*dx))/(12*(dx^2))
central_difference = 60.5437
fpp = funpp(x0)
fpp = 60.5440
  3 件のコメント
J. Alex Lee
J. Alex Lee 2021 年 6 月 12 日
it is not natural to order it that way (from right node to left note). But it should still work:
fun = @(x) x.^3+sin(x);
dx = 0.5;
x0 = 10;
cb = [2,-5,4,-1];
xb = x0 - (0:3)'*dx
xb = 4×1
10.0000 9.5000 9.0000 8.5000
fb = fun(xb);
fbpp = cb*fb/dx^2 % This will not be 60.5508
fbpp = 60.5508
Anna Lin
Anna Lin 2021 年 6 月 12 日
Thank you.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSymbolic Math Toolbox についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by