speed of rand vs randi

조회 수: 6 (최근 30일)
Jonathan
Jonathan 2011년 11월 11일
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
tic
randi(2,1000000,1) == 1;
toc
tic
rand(1000000,1) < 0.5;
toc
Elapsed time is 0.037818 seconds.
Elapsed time is 0.018022 seconds.

채택된 답변

Jan
Jan 2011년 11월 11일
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.
  댓글 수: 3
Jan
Jan 2011년 11월 11일
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:
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
Jonathan
Jonathan 2011년 11월 17일
After doing some other research on this and asking around, I think this is a good explanation. Thank you Jan.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by