How to overcome reaching NaN in trying to write Secant Method?
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Roei Calif
il 13 Lug 2021
Commentato: Mathieu NOE
il 15 Lug 2021
Hello,
My friend and I are trying to write a code that will represent Secant Method for finding roots for functions.
After receiving x0, x1 (initial approximations), the number of iterations and the function from the user, this is how we wrote the code:
while i <= iter
x = x1-y1*(x1-x0)/(y1-y0);
i = i+1;
if isnan(x)
x = x1;
break
end
x0=x1; x1=x;
y0=f(x0); y1=f(x1);
end
We put an "if isnan(x)" because if not x turns out to be NaN with many iterations. The problem is that by doing so, we are actually limiting the number of iterations and cannot reach a more approximate value for the root.
We think this happens because as iterations proceed, x1 and x0 (as well as y1 and y0) become very close, to the point of 0/0.
Do you have any idea about how can we execute the function without limiting the number of iterations, and without getting to NaN?
Thanks in advance.
0 Commenti
Risposta accettata
Mathieu NOE
il 13 Lug 2021
hello
there is one point that you missed , is to break / stop the iteration as soon as the variation of x becomes lower than a given tolerance.
this is explained in the code below :
% MATLAB Code of Secant Method
clearvars;
clc;
f=inline('x^2-2');
x0=0;
x1=1;
tol=1e-6;
itr=100;
p=0;
for i=1:itr
x2=(x0*f(x1)-x1*f(x0))/(f(x1)-f(x0));
if abs(x2-x1)<tol
p=1;
k=i;
break;
else
x0=x1;
x1=x2;
end
end
if p==1
fprintf('Solution is %f at iterations %i',x2,k)
else
fprintf('No convergent solution exist in the given number iteration')
end
Più risposte (0)
Vedere anche
Categorie
Scopri di più su MATLAB Report Generator in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!