Newton's method gives NaN. Can someone improve my code?
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Luca Grillo
am 9 Aug. 2024
Bearbeitet: Torsten
am 9 Aug. 2024
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
Llimit=f(0)
Ulimit=f(1)
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
0 Kommentare
Akzeptierte Antwort
Torsten
am 9 Aug. 2024
Bearbeitet: Torsten
am 9 Aug. 2024
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.
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!