Newton method calculations using loops??stuck!!

hello I am asked to create a function which calculates value of rn=next value of r by giving rc= current value of r and n. here is my function
function rn=NewtonMethod(rc,n)
%rc=current approximation of r
%rn=next approximation of r
rc=input('enter the r value ');
n=input('enter the n value ');
rn= rc+((1-rc)^n-rc)/n*((1-rc)^n-1)+1 ;
end
this code is okay. now i am asked to write a code starting with r and repeat NewtonFunction value until the absolute difference between rn and rc is less than 10^-6. I have no idea what to do in this part, so far I have tried this
rc=input('give an initial approximation for r: ');
n=input('give a n value: ');
while abs(rn-rc)>=10^-6
NewtonMethod(rc,n)
end

답변 (1개)

James Tursa
James Tursa 2015년 11월 17일
편집: James Tursa 2015년 11월 17일

0 개 추천

You are close. You need to get the result of your NewtonMethod call into the variable rn so you can do the comparison. You also need to replace rc with rn at each iteration.
Also, for while loops like this it is often a good idea to put in a counter to stop the loop after a certain number of iterations to prevent an infinite loop. E.g.,
rc = input('give an initial approximation for r: ');
n = input('give a n value: ');
rn = NewtonMethod(rc,n);
k = 0;
kmax = 1000;
while abs(rn-rc)>=10^-6
rc = rn;
rn = NewtonMethod(rc,n);
k = k + 1;
if( k > kmax )
warning('Max iterations reached without convergence');
break;
end
end
fprintf('rn = %f iterations = %d \n',rn,k);
And at the same time comment out the input lines in the NewtonMethod function.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2015년 11월 17일

편집:

2015년 11월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by