C ++ random number generation

For example, the following expression:

r = (rand() % 10)+1;

Generates a random number from 1-10.

How can we make it generate random numbers from 0-10?

Thank.

+3
source share
3 answers

You are almost there! The function rand()returns a random value in a rather large range (from 0 to RAND_MAX). Using the module operator reduces it down to a smaller range (from 0 to 9, since you are modding by 10), and then +1 moves this value from 1 to 10.

To get values ​​from 0 to 10, you can take randand change its value to 11:

r = rand() % 11;

In general, to get random values ​​in the range [0, n], you can write

r = rand() % (n + 1);

, , [k, n + k],

r = rand() % (n + 1) + k;

, , , modding rand() . ( ), , , rand().

+12

+1 0. 11 , 11 10.

r = rand() % 11;

, PRNG, .

rand() . . .

A Mersenne twister , Well512, , .

, PRNG , PRNG. ( ) , . , .

+10

Creating a uniform distribution is much simpler and fewer errors in C ++ 11 using std :: uniform_real_distribution or for the integer case std :: uniform_int_distribution . Here is an example using std :: uniform_real_distribution, which displays simple graphics to give a rough demonstration that it is uniform:

#include <iostream>
#include <iomanip>
#include <string>
#include <random>

int main()
{
    std::random_device rd;

    //
    // Engines 
    //
    std::mt19937 e2(rd());
    //std::knuth_b e2(rd());
    //std::default_random_engine e2(rd()) ;

    std::uniform_real_distribution<> dist(0, 10);

    const int nstars=95;     // maximum number of stars to distribute
    const int nintervals=10; // number of intervals

    int p[nintervals]={};

    for (int i=0; i<100000; ++i)
    {
      double number = dist(e2);
      ++p[int(number)];
    }

    std::cout << std::fixed; std::cout.precision(1);

    for (int i=0; i<nintervals; ++i)
    {
      std::cout << float(i) << "-" << std::setw(4) << float(i+1) << ": ";
      std::cout << std::string(p[i]*nstars/100000,'*') << std::endl;
    }

    return 0 ;
}

Example result:

0.0- 1.0: *********
1.0- 2.0: *********
2.0- 3.0: *********
3.0- 4.0: *********
4.0- 5.0: *********
5.0- 6.0: *********
6.0- 7.0: *********
7.0- 8.0: *********
8.0- 9.0: *********
9.0-10.0: *********

Some of the code examples were taken from this reference .

+4
source

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


All Articles