Newton method calculations using loops??stuck!!
Show older comments
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
Answers (1)
James Tursa
on 17 Nov 2015
Edited: James Tursa
on 17 Nov 2015
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.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!