problem executing while loop
2 ビュー (過去 30 日間)
古いコメントを表示
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
採用された回答
Azzi Abdelmalek
2012 年 10 月 9 日
編集済み: Azzi Abdelmalek
2012 年 10 月 10 日
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 件のコメント
Azzi Abdelmalek
2012 年 10 月 9 日
but if you want to quit a loop after a certain number of itteration, we can add another condition
その他の回答 (2 件)
Sachin Ganjare
2012 年 10 月 9 日
n should be initialized with proper value, probabaly zero.
Hope it helps
0 件のコメント
Amateuromania
2012 年 10 月 9 日
編集済み: Walter Roberson
2012 年 10 月 9 日
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)
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!