forward, backward, central finite differences with step sizes.

조회 수: 69 (최근 30일)
Steven Deng
Steven Deng 2022년 10월 20일
댓글: ahmed 2023년 5월 20일
I have to develop a code that can differentiate functions by using forward, backward, and central finite difference approaches, and I need to use varying step sizes to make the program run at higher accuracies. I also need to show an analytical solution showing the exact solution. So far I have this:
clc; clear; close all;
Fun = @(x) x.^2; %function
dFun = @(x) 2.*x; %derivative
x=linspace(-3,3,101); %from x = -3 to 3
F=Fun(x);
h=x(2)-x(1);
xCentral=x(2:end-1); %Central Difference Approach
dFCentral=(F(3:end)-F(1:end-2))/(2*h);
xForward=x(1:end-1); %Forward Difference Approach
dFForward=(F(2:end)-F(1:end-1))/h;
xBackward=x(2:end); %Backward Difference Approach
dFBackward=(F(2:end)-F(1:end-1))/h;
plot(x,dFun(x)); %Exact solution
hold on
plot(xCentral,dFCentral,'r')
plot(xForward,dFForward,'k');
plot(xBackward,dFBackward,'g');
legend('Analytic','Central','Forward','Backward') %Plot everything
However, I dont know how to implement a step size into the program, how would I do this?
  댓글 수: 1
ahmed
ahmed 2023년 5월 20일
use matlab code to find the approximation of the solution sinh-1(x) by using backward

댓글을 달려면 로그인하십시오.

답변 (1개)

Davide Masiello
Davide Masiello 2022년 10월 21일
편집: Davide Masiello 2022년 10월 21일
I took the liberty to give you an example with a different function, because the one in your question has a constant slope and different step sizes produce the same result, hence it's difficult to visualize. Also, I did it only for the central difference case.
Fun = @(x) x.^3; % Function
dFun = @(x) 3*x.^2; % First order derivative
fplot(dFun,[-3,3],'.'),hold on % Plot of first order derivative
h = [1 0.5 0.1]; % Three different step sizes
for i = 1:3 % Loops over step sizes
x = -3:h(i):3; % Creates x array depending on step size
xd = x(2:end-1); % Removes boundaries (can't be approximated with central difference)
dFc = (Fun(x(3:end))-Fun(x(1:end-2)))/(2*h(i)); % Central difference scheme
plot(x(2:end-1),dFc) % Plot the result
end
legend('Analytic','h = 1','h = 0.5','h = 0.1','Location','best')

카테고리

Help CenterFile Exchange에서 Descriptive Statistics and Visualization에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by