problem executing while loop

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

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)

댓글을 달려면 로그인하십시오.

 채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2012년 10월 9일
편집: Azzi Abdelmalek 2012년 10월 10일

0 개 추천

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

GreGG
GreGG 2012년 10월 9일
when i do that the code never enters the loop it just displays 1.0e^-7
am i using the absolute value comand right?
Azzi Abdelmalek
Azzi Abdelmalek 2012년 10월 9일
편집: Azzi Abdelmalek 2012년 10월 9일
No, it enter the loop once, check the value of x. t's changed de tol. The problem is in your code, or it depends on the value of a and x
initialize n to x
n=x
GreGG
GreGG 2012년 10월 9일
now i get an infinite loop
Azzi Abdelmalek
Azzi Abdelmalek 2012년 10월 9일
does'nt mean there is an error in your code.
Azzi Abdelmalek
Azzi Abdelmalek 2012년 10월 9일
but if you want to quit a loop after a certain number of itteration, we can add another condition
GreGG
GreGG 2012년 10월 9일
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?

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Sachin Ganjare
Sachin Ganjare 2012년 10월 9일

0 개 추천

n should be initialized with proper value, probabaly zero.
Hope it helps
Amateuromania
Amateuromania 2012년 10월 9일
편집: Walter Roberson 2012년 10월 9일

0 개 추천

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!

Translated by