Uniformly distributed random numbers coprime to 2

Specific example

I need to create a random number from 0 to 2 inclusive. (or randomly choose between -1, 0 and 1).

A naive approach would be to do something like rand() mod 3where rand()returns an integer. This approach will not generate statistically random numbers if the upper bound is rand()not coprime (and the lower bound is 0).

For example, if rand () returned 2 bits (from 0 to 3 inclusive), the module would display:

0 → 0
1 → 1
2 → 2
3 → 0

This skew in the 0 direction will obviously be much less if more bits are returned, but despite this, the skew remains.

General question

Is there a way to generate a uniformly distributed random number between 0 and n-1 inclusive, where n is coprime with 2?

+3
source share
4 answers

A common approach is to discard random values ​​above the last full cycle and simply request a new random number.

+3
source

This may help pick your early evaluation of rand () as k * n, where k is an integer. Thus, the result will be evenly distributed provided that rand () is a good random generator.

If it is not possible to reduce the upper bound, you can choose k so that k * n is as close as possible to the upper bound of rand () and discards the results above this number, trying again.

+2

.

, RNG N . mod n * floor (MAX/n)

+1

: .

, , x, 0.0 <= x < 1.0, 3 . 0, 1 2, .

0

Source: https://habr.com/ru/post/1711527/


All Articles