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
2 ビュー (過去 30 日間)
古いコメントを表示
%%%% 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 件のコメント
回答 (1 件)
Askic V
2022 年 11 月 15 日
編集済み: Askic V
2022 年 11 月 15 日
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 件のコメント
Askic V
2022 年 11 月 15 日
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
参考
カテゴリ
Help Center および File Exchange で Number Theory についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!