Error in line 12. I cant use 'inline' command. How to fix it? There are 3 iterations. Equation is f(x)= e^-x-x and the derivative is -e^-x-1. Using Newton Raphson Method
8 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
%%%% MATLAB CODE of Newton Raphson Method
%%% Method for finding the ROOT of
%%%% equation f(x)= exp(1)^-x-x
format short
clear
clc
syms x
% Write the function here
% f= @ (x) exp(1)^-x-x;
f = @ (x) exp(1)^-x-x;
df = diff (f,x);
dfx = inline(df); %derivative of funtion df
x0 = 0; %initial guess
n = 4; % number of decimal places
Variables={'Iter','x','f_x0','Error'};
iter = 1;
err = abs (f(x0));
epsilon = 5*10^(-n-1);
itermax = 70;
HG = [];
if dfx(x0)<10^(-9)
disp('Wrong choice of initial Guess');
else
while (iter<=itermax && err>epsilon)
x1 = x0-f(x0)/dfx(x0);
err = abs (f(x0));
HG = [iter x0 f(x0) err];
iter = iter+1;
x0 = x1;
end
end
disp ('======================================')
disp ('Output Table with Iteration wise')
Result= array2table(HG);
Result.Properties.VariableNames(1:size(HG,2)) = Variables
x0 = x0-rem(x0,10^-n);
fprintf('Converged solution after %d iterations \n',iter);
fprintf('Root is %1.5f \n',x0)
1 commentaire
Réponses (1)
Askic V
le 15 Nov 2022
Modifié(e) : Askic V
le 15 Nov 2022
Try this:
format short
clear
clc
syms x
% Write the function here
% f= @ (x) exp(1)^-x-x;
f = @ (x) exp(1)^-x-x;
df = diff (f,x);
dfx = @(x) eval(df);
%inline(df); %derivative of funtion df
% inline will be removed in future releases
x0 = 0; %initial guess
n = 4; % number of decimal places
Variables={'Iter','x','f_x0','Error'};
iter = 1;
err = abs (f(x0));
epsilon = 5*10^(-n-1);
itermax = 70;
HG = [];
% Use abs function here!
if abs ( dfx(x0) ) < 10^(-9)
disp('Wrong choice of initial Guess');
else
while (iter<=itermax && err>epsilon)
x1 = x0-f(x0)/dfx(x0);
err = abs (f(x0));
HG = [iter x0 f(x0) err];
iter = iter+1;
x0 = x1;
end
end
disp ('======================================')
disp ('Output Table with Iteration wise')
Result= array2table(HG);
Result.Properties.VariableNames(1:size(HG,2)) = Variables
x0 = x0-rem(x0,10^-n);
fprintf('Converged solution after %d iterations \n',iter);
fprintf('Root is %1.5f \n',x0)
2 commentaires
Askic V
le 15 Nov 2022
The number of iterations generally depends of initial guess and the epsilon.
In your while loop the stop criteria is maximum iteration reached or error is below predifed epsilon. If you want 3 iterations, the easiest way (for the same initial guess 0) is to make epsilon larger, such as:
epsilon = 5*10^(-n+1);
This would produce the following result:
Iter x f_x0 Error
____ _______ _________ _________
3 0.56631 0.0013045 0.0013045
Voir également
Catégories
En savoir plus sur Number Theory dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!