problem executing while loop

7 views (last 30 days)
GreGG
GreGG on 9 Oct 2012
im writing a script to solve the square root of a number using halley's method
my equations: y=(1/a)*x^2
n = (x/8)*(15-(y)*(10-3*(y)))
then n becomes the new x and the equation repeats
my problem is its not looping it runs through once and then stops
clc
clear
a = input('number ');
x = input('guess ');
tol = 0.0000001;
while (abs(n-x)<=tol)
y=(1/a)*x^2;
n = ((x/8)*(15-(y)*(10-3*(y))));
x=n;
end
disp(n)
i want the loop to stop when the number is accurate to 6 decimal places. what am i doing wrong
very new to ML
  1 Comment
GreGG
GreGG on 9 Oct 2012
ended up figuring it out
clc
clear
a = input('number ');
x = input('guess ');
tol = 0.000001;
dif=inf;
while dif>=tol
y=(1/a)*x^2;
n = ((x/8)*(15-y*(10-3*y)));
dif= (abs(n-x));
disp(n)
x=n;
end
disp(n)

Sign in to comment.

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 9 Oct 2012
Edited: Azzi Abdelmalek on 10 Oct 2012
insert before while n=x;
clc
clear
a = input('number ');
x = input('guess ');
tol = 0.0000001;
n=x
while (abs(n-x)<=tol)
y=(1/a)*x^2;
n = ((x/8)*(15-(y)*(10-3*(y))));
x=n;
end
disp(n)
  7 Comments
Azzi Abdelmalek
Azzi Abdelmalek on 9 Oct 2012
but if you want to quit a loop after a certain number of itteration, we can add another condition
GreGG
GreGG on 9 Oct 2012
eventually i want to adjust the code so that the user can decide how many accurate decimal places they get each loop adds 2 correct decimals (or something like that i dont remember right now)...am i on the right track for this?

Sign in to comment.

More Answers (2)

Sachin Ganjare
Sachin Ganjare on 9 Oct 2012
n should be initialized with proper value, probabaly zero.
Hope it helps

Amateuromania
Amateuromania on 9 Oct 2012
Edited: Walter Roberson on 9 Oct 2012
You haven't declared n. First calculate n then check the condition much like the do while loop.
You can use something like this:
clc;
clear;
a = input('number ');
x = input('guess ');
tol = 0.0000001;
y=(1/a)*x^2;
n = ((x/8)*(15-(y)*(10-3*(y))));
x=n;
while (abs(n-x)<=tol)
y=(1/a)*x^2;
n = ((x/8)*(15-(y)*(10-3*(y))));
x=n;
end;
disp(n)

Community Treasure Hunt

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

Start Hunting!