MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today
Asked by Sabarinathan Vadivelu on 27 Aug 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

Answer by Walter Roberson on 27 Aug 2012

Accepted answer

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

Note: please take time to review the following: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F

Show 2 older comments

Sabarinathan Vadivelu on 27 Aug 2012

How can I overcome this problem? How to satisfy that condition? It should be a +b = 1. No other values should come.

Jan Simon on 27 Aug 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.

## 1 Comment

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/46776#comment_96273

I found that sometimes the sum was exceeding 1 or less than 1. Why?