Finding the root of a real number using Newton-Raphson Method [Homework Help]

I'm working on this project for school that requires me to find the real root of a number using the Newton Raphson Method (equation given is x1 = 0.5 * (x + (R/x)). Here is my code:
R=10;
x=3;
iter = 0;
max_iter = 10;
perc_tol = 5;
answer = 0;
while iter < max_iter || answer > perc_tol
x = (0.5*(x+(R/x)));
no_iter = no_iter + 1;
answer = ((abs((x1-x)/(x1)))*100);
end
disp(x1)
disp(iter)
The problem I keep getting is it becomes an infinite loop (because the answer never becomes <= perc_tol I assume) and if I keep only the 'iter < max_iter' then it only performs the loop once , no matter the defined number of iterations. Any suggestions?

Answers (1)

while no_iter < max_iter && answer > perc_tol
By the way, what is the xinew that you
disp(xinew)

4 Comments

xinew = x1 and no_iter = iter, just changing the variable names from my code as they need to be stupidly long for the hand in.
When I change it to && my I get the error that "x1 is undefined in line 14" ('disp(xinew)')
How can you be getting an error about x1 being undefined on a line that contains no reference to x1 ?
We need the real code and the real error messages.
Code:
R=10;
xi=3;
no_iter = 0;
max_iter = 10;
perc_tol = 5;
answer = 0;
while no_iter < max_iter && answer > perc_tol
xinew = (0.5*(xi+(R/xi)));
no_iter = no_iter + 1;
answer = ((abs((xinew-xi)/(xinew)))*100);
end
disp(xinew)
disp(no_iter)
Error:
Undefined function or variable 'xinew'.
Error in a4_test2b (line 14)
disp(xinew)
You start with answer = 0 and you test it against perc_tol which is 5. 0 > 5 is false so your loop body is not run even once.
Suggestion: initialize answer to infinity.

Sign in to comment.

Asked:

on 5 Dec 2015

Commented:

on 7 Dec 2015

Community Treasure Hunt

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

Start Hunting!