Effacer les filtres
Effacer les filtres

Displaying the answer of Newton's method for multiple roots?

4 vues (au cours des 30 derniers jours)
Roger L
Roger L le 26 Oct 2016
Commenté : Roger L le 27 Oct 2016
Hello. I'm looking for a way to display my solutions for a Newton's method. There are 4 roots in my interval.
roots=[-0.0505 1.3232 1.3636 2.3333] %initial guesses corresponding to the 4 roots.
The trouble i'm having is that the script only shows the results for first root using -0.0505, while m reaches the value 4. I don't know why it cant display the other results for m=2,3,4. What could be the problem? Thanks!
m=1;
while m<=length(roots)
x=roots(m); % initial guess for the root
tol=10e-8;
fprintf(' k xk fx dfx \n');
for k=1:50 % iteration number
fx=sin(x^(2))+x^(2)-2*x-0.09;
dfx=(2*(x*cos(x^2)+x-1));
fprintf('%3d %12.8f %12.8f %12.8f \n', k,x,fx,dfx);
x=x-fx/dfx;
m=m+1;
if abs(fx/dfx)<tol
return;
end
end
end
RUN
k xk fx dfx
1 -0.05050505 0.01611162 -2.20201987
2 -0.04318831 0.00010707 -2.17275307
3 -0.04313903 0.00000000 -2.17255596

Réponse acceptée

Sophie
Sophie le 26 Oct 2016
for k=1:50
fx=sin(x^(2))+x^(2)-2*x-0.09;
dfx=(2*(x*cos(x^2)+x-1));
fprintf('%3d %12.8f %12.8f %12.8f \n', k,x,fx,dfx);
x=x-fx/dfx;
m=m+1;
You increase m on each iteration step.
  3 commentaires
Sophie
Sophie le 26 Oct 2016
Modifié(e) : Sophie le 26 Oct 2016
I've found the mistake. Here Newton function returns only results from the last iteration. So that you have to make k,x,fx,dfx in the functions vectors.
Roger L
Roger L le 27 Oct 2016
Thanks Sophie. It turns out that the loop wasn't working because of the "return;" command in the if loop. I changed that to a break command and it fixed the code.

Connectez-vous pour commenter.

Plus de réponses (1)

Sophie
Sophie le 26 Oct 2016
Obtained solution: Main code
m=1;
fprintf(' k xk fx dfx \n');
roots=[-0.0505 1.3232 1.3636 2.3333];
while m<=length(roots)
k=[];x=[];fx=[];dfx=[];
[k,x,fx,dfx]=Newton(roots(m));
for i=1:length(k)
fprintf('%3d %12.8f %12.8f %12.8f \n', k(i),x(i),fx(i),dfx(i));
end
m=m+1;
fprintf('\n');
end
Newton
function [kk,x,fx,dfx]=Newton(initialguess)
x=initialguess;
kk=[];fx=[];dfx=[];
tol=10e-8;
for k=1:50 % iteration number
kk(end+1)=k;
fx(end+1)=sin(x(end)^(2))+x(end)^(2)-2*x(end)-0.09;
dfx(end+1)=(2*(x(end)*cos(x(end)^2)+x(end)-1));
x(end+1)=x(end)-fx(end)/dfx(end);
if abs(fx(end)/dfx(end))<tol
return;
end
end
end

Catégories

En savoir plus sur Particle & Nuclear Physics dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by