Random numbers from -10 to 10 in C ++

How to make random numbers between -10 and 10 in C ++?

srand(int(time(0)));//seed
for(int i  = 0; i < size; i++){
 myArray[i] = 1 + rand()  % 20 - 10;//this will give from -9 to 10
 myArray2[i] =rand()  % 20 - 10;//and this will -10 to 9
}
+3
source share
11 answers

You need a range of 21, not 20, so do something like this:

x = rand() % 21 - 10;
+8
source

To get an even distribution, you must first divide RAND_MAX

static_cast<int>(21*static_cast<double>(rand())/(RAND_MAX+1)) - 10

using

rand() % 21 - 10;

faster and often used in applications, but the given distribution is not homogeneous. The function rand()generates numbers from 0to RAND_MAX. If RAND_MAX%21!=0lower numbers are more likely to be generated.

You can also use the modulo method, but with some random numbers discarded:

int randMax = RAND_MAX - RAND_MAX%21;

int p=RAND_MAX+1;
while(p>randMax)
        p=rand();

x=p%21 - 10;

Edit (comments from Johannes and Steve):

RAND_MAX , , - , .

Boost Random Library ( Danvil), .

+10

Boost Random Number Library. , , . , boost .

// based on boost random_demo.cpp profane demo
#include <iostream>

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>

int main() {
  boost::mt19937 gen(42u); // seed generator
  boost::uniform_int<> uni_dist(-10, 10); // random int from -10 to 10 inclusive
  boost::variate_generator<boost::mt19937&, boost::uniform_int<> > 
    uni(gen, uni_dist); // callable

  for(int i = 0; i < 10; i++)
    std::cout << uni() << ' ';
}

:

-3 6 9 -7 5 6 2 2 -7 -1 

: ++ 11.

+8

[0,20] rand() % 21, 10 .

+4

++ 11 random (. rand() ). [-10,10]:

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;

    std::mt19937 e2(rd());

    std::uniform_int_distribution<int> dist(-10, 10);

    for (int n = 0; n < 10; ++n) {
            std::cout << dist(e2) << ", " ;
    }
    std::cout << std::endl ;
}
+3

"u" (0,1), [-10,10]:

-10*u + (1-u)*10
+1

fencepost - , , , , ; :

myArray2[i] =rand()  % 21 - 10;//and this will -10 to +10
0

rand() % 21 - 10

0

If you want the numbers to be in the range [-10, 10], then you have 21 possible numbers.

(rand() % 21) - 10;
0
source

How about (rand ()% 21) - 10;

Or am I missing something?

0
source

use this will be:

int x = (rand() % 21) - 10;
cout<<x;
0
source

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


All Articles