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

7 次查看(过去 30 天)
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

采纳的回答

Sophie
Sophie 2016-10-26
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 个评论
Sophie
Sophie 2016-10-26
编辑:Sophie 2016-10-26
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 2016-10-27
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.

请先登录,再进行评论。

更多回答(1 个)

Sophie
Sophie 2016-10-26
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

类别

Help CenterFile Exchange 中查找有关 Performance and Memory 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by