How do I create a random number from a range that includes zero?
14 ビュー (過去 30 日間)
古いコメントを表示
I'm looking for a way to create uniformly distributed random numbers between 0 and 1 (including 0, excluding 1). The Matlab function rand() excludes zero. It is using the range (0, 1).
In Python/Numpy the functions random.random() is using the range [0.0, 1.0). That is why I hope it is mathematically/informatically possible to implement such random numbers.
My first thought was to subtract the default minimum value of rand() so that zero is actually possible. However, I couldn't find such a minimum value.
Any ideas? Many thanks in advance!
採用された回答
Jan
2018 年 8 月 15 日
編集済み: Jan
2020 年 12 月 15 日
For a double with 32 bit used random bits and [0, 1):
r = randi([0, 4294967295]) / 4294967296.0 % constants: 2^32-1 and 2^32
[TYPO FIXED: "2^31-1" ==> "2^32-1"]
With 53 bit precision (as by rand()) and [0, 1):
a = randi([0, 4294967295]) * 32; % Constant: 2^32-1
b = randi([0, 4294967295]) * 64;
r = (a * 67108864.0 + b) / 9007199254740992.0; % Constants: 2^26, 2^53
For 53 bit precision (as by rand()) and [0, 1]:
r = (a * 67108864.0 + b) / 9007199254740991.0; % Constants: 2^26, 2^53-1
I assume that this is not efficient, because I do not know the method to calculate randi([0, 4294967295]). Creating 32 random bits is cheap, but the limitation to a certain interval is expensive, because the modulo operation would be flawed. In the case of [0, 2^32-1] there is no need to limit the interval, because the 32 random bits can be used directly.
I'm planning to publish a Mersenne-Twister MEX function, which provides the [0,1) and [0,1] intervals directly.
3 件のコメント
Keonwook Kang
2020 年 12 月 15 日
In your script for a double with 32 bit, you wrote the constants 2^31-1 and 2^32. But I guess what you meant is 2^31-1 and 2^31. And the numbers are 2147483647 and 2147483648. Then, the script must be modified as
r = randi([0, 2147483647]) / 2147483648 % constants: 2^31-1 and 2^31
Am I right?
Jan
2020 年 12 月 15 日
@Keonwook Kang: Thanks for finding this typo. Actually only the comment was wrong and the numbers are "2^32-1 and 2^32".
randi([0, 4294967295]) produces numbers between 0 and (binary) 11111111 11111111 11111111 11111111 (32 bits). This means, that 2^32-1 is the correct upper limit and dividing it by 2^32 results in an output of [0, 1).
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Random Number Generation についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!