How to overcome reaching NaN in trying to write Secant Method?
    6 views (last 30 days)
  
       Show older comments
    
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 Comments
Accepted Answer
  Mathieu NOE
      
 on 13 Jul 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
More Answers (0)
See Also
Categories
				Find more on Logical in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
