Why does my rand function not seem to work?

limit = 0.3266;
s = 0;
counter = 0;
while 1
tmp = rand;
disp(tmp)
if tmp == limit
break
end
counter = counter + 1;
end
disp(counter);
Using tmp > limit, returns a value for counter, but if i did tmp == limit, it seems to go into an endless loop. First I thought the number 0.3266 had not been found until i wrote each randomly generated number to a file and later checked to discover that there's been more than 100 occurences of 0.3266 in about 5million counters, but the loop doesn't stop, Please is there something I'm doing wrong?

2 件のコメント

Jorge Mario Guerra González
Jorge Mario Guerra González 2019 年 3 月 4 日
編集済み: Jorge Mario Guerra González 2019 年 3 月 4 日
Because you are storing and displaying the numbers with only some decimals, there are more didigts, it would be weird if they match.
If you really want to do that operation, you should cast that random value to an int or something.
Jeremiah Abimbola
Jeremiah Abimbola 2019 年 3 月 4 日
Thanks for your explanation, I got the idea

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

 採用された回答

Torsten
Torsten 2019 年 3 月 4 日

1 投票

You will never hit 0.3266 exactly using the "rand" command.
You can use
if abs(tmp-limit) < 1e-6
or something similar in your code instead of
if tmp == limit
Best wishes
Torsten.

1 件のコメント

Jeremiah Abimbola
Jeremiah Abimbola 2019 年 3 月 4 日
Thanks, I've learnt something new

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品

リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by