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

조회 수: 5 (최근 30일)
Roger L
Roger L 2016년 10월 26일
댓글: Roger L 2016년 10월 27일
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