Consider the following example. a and b are two random variables. The loop will exit if and only if a+b=1. Is it true or false?
a=rand;
b=rand;
while(a+b == 1)
a=rand;
b=rand;
end

1 件のコメント

Sabarinathan Vadivelu
Sabarinathan Vadivelu 2012 年 8 月 27 日
I found that sometimes the sum was exceeding 1 or less than 1. Why?

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

 採用された回答

Walter Roberson
Walter Roberson 2012 年 8 月 27 日

0 投票

While executes as long as the given condition is true, so the loop would only execute as long as the sum was 1.

5 件のコメント

Sabarinathan Vadivelu
Sabarinathan Vadivelu 2012 年 8 月 27 日
編集済み: Sabarinathan Vadivelu 2012 年 8 月 27 日
But sir, I found that when adding both values I'm getting a value greater than 1.
a=0.7849 and b=0.9728. this value I got one time.
Walter Roberson
Walter Roberson 2012 年 8 月 27 日
If the sum was greater than 1, then a+b == 1 would be false, so your loop as written would not execute, so the values would be left unchanged.
Sabarinathan Vadivelu
Sabarinathan Vadivelu 2012 年 8 月 27 日
How can I overcome this problem? How to satisfy that condition? It should be a +b = 1. No other values should come.
Jan
Jan 2012 年 8 月 27 日
編集済み: Jan 2012 年 8 月 27 日
If a+b must be 1, simply use:
a = rand; b = 1 - a;
It is extremely unlikely that two random numbers will have a sum of 1. I think the probability is in the magnitude of 10^-53. Therefore rejecting the values until the sum equals 1 will take a looong time.
Walter Roberson
Walter Roberson 2012 年 8 月 27 日
a=rand;
b=rand;
while(a+b ~= 1)
a=rand;
b=rand;
end

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeElectrical Block Libraries についてさらに検索

製品

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by