Looping until conditions met

54 ビュー (過去 30 日間)
Espen
Espen 2014 年 11 月 20 日
編集済み: Espen 2014 年 11 月 20 日
I have a (rather ineffective, but still does it's job) code doing a method I can only call "middlepoint method" as I lack any direct translation. But in basics it's an alternative method to Newtons Method and does the same thing but with MANY more repeats required.
Anyway here is the loop of the code itself; (note that before this there are a few lines containing the function and certain values, but they aren't important)
for n=1:inf
if f(y)<0
b=y
y=y/2
else y=((b+y)/2)
end
if f(y)==0
break
end
end
I know it's not pretty and might even be VERY inefficient, but it actually produces the answer down to 10^-15 accuracy. It takes 646 loops. Now normally that would be absolutely perfect, but the task itself only asks me to make a code that loops until the accuracy is within 10^-5 and how many loops this takes.
What I am wondering is this; is there something I can type in the "if f(y)" line (the one that breaks the for loop if certain conditions are met) that makes the loop stop after f(y) produces an answer between 0 to 0.0001 range rather than exactly 0?
  1 件のコメント
the cyclist
the cyclist 2014 年 11 月 20 日
You might also consider doing this with a while loop. Type
doc while
into the command window for details.

サインインしてコメントする。

採用された回答

Guillaume
Guillaume 2014 年 11 月 20 日
Wouldn't that just be
if abs(f(y)) < 0.0001
break;
end
You shouldn't be using == to compare floating point values anyway. Particularly, if one of them come out as a result of a calculation.
  1 件のコメント
Espen
Espen 2014 年 11 月 20 日
編集済み: Espen 2014 年 11 月 20 日
Yes, that's the command I was looking for. Thank you very much! And as for the f(y)==0 that was just there because that was the only one that made the loop go until a certain point was met.
Since the function had both negative and positive side (Like f(0.8) could give me -0.62 while f(0) gives me 1) just using one where f(y)>(some number) or f(y)<(some number) just made it stop far too prematurely since it would reach those levels interchangibly.
But again, I appreciate your time and help!

サインインしてコメントする。

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 11 月 20 日
You can use a while loop

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by