# How to overcome reaching NaN in trying to write Secant Method?

조회 수: 6(최근 30일)
Roei Calif 2021년 7월 13일
댓글: Mathieu NOE 2021년 7월 15일
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?

댓글을 달려면 로그인하십시오.

### 채택된 답변

Mathieu NOE 2021년 7월 13일
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
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
Mathieu NOE 2021년 7월 15일
My pleasure

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!