Following True or False?

1 visualizzazione (ultimi 30 giorni)
Sabarinathan Vadivelu
Sabarinathan Vadivelu il 27 Ago 2012
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 Commento
Sabarinathan Vadivelu
Sabarinathan Vadivelu il 27 Ago 2012
I found that sometimes the sum was exceeding 1 or less than 1. Why?

Accedi per commentare.

Risposta accettata

Walter Roberson
Walter Roberson il 27 Ago 2012
While executes as long as the given condition is true, so the loop would only execute as long as the sum was 1.
  5 Commenti
Jan
Jan il 27 Ago 2012
Modificato: Jan il 27 Ago 2012
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 il 27 Ago 2012
a=rand;
b=rand;
while(a+b ~= 1)
a=rand;
b=rand;
end

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by