forward, backward, central finite differences with step sizes.
28 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
ahmed
am 20 Mai 2023
use matlab code to find the approximation of the solution sinh-1(x) by using backward
Antworten (1)
Davide Masiello
am 21 Okt. 2022
Bearbeitet: Davide Masiello
am 21 Okt. 2022
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')
0 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!