Will this give me the correct random numbers based on these probabilities? C ++

the code:

int random = (rand() % 7 + 1)
if (random == 1) { } // num 1
else if (random == 2) { } // num 2
else if (random == 3 || random == 4) { } // num 3
else if (random == 5 || random == 6) { } // num 4
else if (random == 7) { } // num 5

Basically, I want each of these numbers with each of these probabilities: 1: 1/7 2: 1/7 3: 2/7 4: 2/7 5: 1/7

Will this code give me the correct results? That is, if it works endlessly, will I get the right frequencies? Is there a shorter way to do this?

+5
source share
5 answers

No, this is actually slightly disabled, due to the way rand () works. In particular, rand returns values ​​in the range [0, RAND_MAX]. Hypothetically suggest that RAND_MAX was ten. Then rand () will give 0 ... 10, and they will be mapped (modulo) to:

0  → 0
1  → 1
2  → 2
3  → 3
4  → 4
5  → 5
6  → 6
7  → 0
8  → 1
9  → 2
10 → 3

, 0-3 , 4-6; . ( 1, ).

RAND_MAX, , 10, , , 7 ( 1). , . .

Boost Random Number Library, , 1-7 . bames53 ++ 11, , ++ 11.

+7

:

float probs[5] = {1/7.0f, 1/7.0f, 2/7.0f, 2/7.0f, 1/7.0f};
float sum = 0;
for (int i = 0; i < 5; i++)
  sum += probs[i]; /* edit */
int rand_M() {
  float f = (rand()*sum)/RAND_MAX; /* edit */
  for (int i = 0; i < 5; i++) {
    if (f <= probs[i]) return i;
    f -= probs[i];
  }
  return 4;
}
+2
int toohigh = RAND_MAX - RAND_MAX%7;
int random;
do { 
    random = rand();
while (random >= toohigh); //should happen ~0.03% of the time
static const int results[7] = {1, 2, 3, 3, 4, 4, 5};
random = results[random%7];

, rand , if.

, , . , , . , , , . ( RNG.)

+2

, rand() , X-, X RAND_MAX% 7. , - rand(). , , .

++ 11 <random>, RNG. :

#include <random>
#include <functional>

auto rand = std::bind(std::uniform_int_distribution<int>(1,7),std::mt19937());

, rand(), 1 7 . ( , .) if-else, std::rand(). <random> . discrete_distribution. 0 n.

// the random number generator
auto _rand = std::bind(std::discrete_distribution<int>{1./7.,1./7.,2./7.,2./7.,1./7.},std::mt19937());
// convert results of RNG from the range [0-4] to [1-5]
auto rand = [&_rand]() { return _rand() +1; };
+2

rand :

, modulo - ( ), , , .


, , ?: ( :).

-1

All Articles