Finding the root of a real number using Newton-Raphson Method [Homework Help]
Show older comments
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)
Walter Roberson
on 5 Dec 2015
Edited: Walter Roberson
on 5 Dec 2015
while no_iter < max_iter && answer > perc_tol
By the way, what is the xinew that you
disp(xinew)
4 Comments
Fraser Fife
on 5 Dec 2015
Edited: Fraser Fife
on 5 Dec 2015
Walter Roberson
on 5 Dec 2015
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.
Fraser Fife
on 5 Dec 2015
Walter Roberson
on 7 Dec 2015
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.
Categories
Find more on Newton-Raphson Method 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!