Newton's method gives NaN. Can someone improve my code?

조회 수: 3 (최근 30일)
Luca Grillo
Luca Grillo 2024년 8월 9일
편집: Torsten 2024년 8월 9일
Hello everybody. I'm using Newton's method to solve a liner equation whose solution should be in [0 1]. Unfortunately, the coe I'm using gives NaN as a result for a specific combination of parameters and I would like to understand if I can improve the code I wrote for my Newton's method. In the specific case I'm considering, I reach the maximum iterations even if the tolerance is very low.
% % % % Script for solving NaN
mNAN= 16.1;
lNAN= 10^-4;
f= @(x) mNAN*x+lNAN*exp(mNAN*x)-lNAN*exp(mNAN);
Fd= @(x) mNAN*(1+lNAN*exp(mNAN*x));
tolNaN=10^-1;
nmax=10^8;
AB0 = 0.5;
[amNAN,nNAN,ierNAN]=newton(f,Fd,AB0,nmax,tolNaN);
amNAN
amNAN = NaN
Llimit=f(0)
Llimit = -982.0670
Ulimit=f(1)
Ulimit = 16.1000
fplot(@(x) mNAN*x+lNAN*exp(mNAN*x)-lNAN*exp(mNAN),[0 1.1])
function [x,n,ier] = newton(f,fd,x0,nmax,tol)
% Newton's method for non-linear equations
ier = 0;
for n = 1:nmax
x = x0-f(x0)/fd(x0);
if abs(x-x0) <= tol
ier = 1;
break
end
x0 = x;
end
end

채택된 답변

Torsten
Torsten 2024년 8월 9일
편집: Torsten 2024년 8월 9일
Your undamped Newton's method throws you from x = 0.5 to x = 46 appr. in the next step. Here, your function cannot be evaluated because of the large exp() term.
Conclusion: Newton's method doesn't converge in all cases.
Try a different initial point x0 in the region where the function is steeper than in 0.5 (e.g. 0.9).
Or use a damping factor 0 < d < 1:
x = x0-d*f(x0)/fd(x0);
Convergence will be slower, but safer.
Further, you should also check whether abs(f(x)) is really small when you break the iteration. abs(x-x0) < tol usually doesn't suffice for the iteration to be converged if your function is steep.
  댓글 수: 1
Luca Grillo
Luca Grillo 2024년 8월 9일
Thank you for your suggestions! I'll try it out and see if it gets better!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Physics에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by