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 Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by