MATLAB Answers

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

17 views (last 30 days)
Roger L
Roger L on 26 Oct 2016
Commented: Roger L on 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

Accepted Answer

Sophie
Sophie on 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 Comments
Roger L
Roger L on 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.

Sign in to comment.

More Answers (1)

Sophie
Sophie on 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

Community Treasure Hunt

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

Start Hunting!

Translated by