How do I create a random number from a range that includes zero?
17 views (last 30 days)
Show older comments
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!
Accepted Answer
Jan
on 15 Aug 2018
Edited: Jan
on 15 Dec 2020
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 Comments
Keonwook Kang
on 15 Dec 2020
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
on 15 Dec 2020
@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).
More Answers (0)
See Also
Categories
Find more on Random Number Generation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!