Following True or False?

1 次查看(过去 30 天)
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
I found that sometimes the sum was exceeding 1 or less than 1. Why?

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2012-8-27
While executes as long as the given condition is true, so the loop would only execute as long as the sum was 1.
  5 个评论
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 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by