Clear Filters
Clear Filters

speed of rand vs randi

4 views (last 30 days)
Jonathan on 11 Nov 2011
I sometimes use "if rand < 0.5" or "if randi(2) == 1" to arbitrarily select one branch or another with equal probability. I ran the following code to see the speed difference between these. Does anyone know why fetching a random double is so much less expensive than fetching a random integer?
Thanks in advance, Jonathan
randi(2,1000000,1) == 1;
rand(1000000,1) < 0.5;
Elapsed time is 0.037818 seconds.
Elapsed time is 0.018022 seconds.

Accepted Answer

Jan on 11 Nov 2011
The algorithms to create random numbers reply 32bit integers usually. A standard method to create a random DOUBLE combines two of them:
a = <INT32_rand>;
b = <INT32_rand>;
r = ((a >> 5) * 67108864.0 + (b >> 6)) / 9007199254740992.0;
Getting an integer <= n with a guaranteed equal distribution is more expensive. You cannot just use MOD or an integer division, because this would result in a bias. You have to draw random numbers until you get one, which is smaller than the largest multiple of n, which is smaller than 2^32-1. Then the modulo-operation is safe. This methods needs branching, which slows down the processor massively.
Jan on 11 Nov 2011
The license conditions of Matlab forbid a reverse engineering.
Matlab uses standard libraries for the creation of random numbers, e.g. mt19937ar, therefore it is documented, that 32-bit integers are created. Some comparisons of the results would reveal the parameters used for the conversion to doubles.
For the conversion to integers there is another efficient method from Magnus Jonsson:
used |= n >> 1;
used |= used >> 2;
used |= used >> 4;
used |= used >> 8;
used |= used >> 16;
// Draw numbers until one is found in [0,n]:
while ((i = RAND_UINT32() & used) > n) ;
The runtime behaviour is equivalent to the method explained above. The Matlab documentation links to this page for details about the Mersenne twister:
Jonathan on 17 Nov 2011
After doing some other research on this and asking around, I think this is a good explanation. Thank you Jan.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!