Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random number from -9 to 9 in C++

just wondering, if I have the following code:

int randomNum = rand() % 18 + (-9);

will this create a random number from -9 to 9?

like image 927
Danny Avatar asked Oct 25 '11 10:10

Danny


4 Answers

No, it won't. You're looking for:

int randomNum = rand() % 19 + (-9);

There are 19 distinct integers between -9 and +9 (including both), but rand() % 18 only gives 18 possibilities. This is why you need to use rand() % 19.

like image 85
NPE Avatar answered Nov 07 '22 16:11

NPE


Do not forget the new C++11 pseudo-random functionality, could be an option if your compiler already supports it.

Pseudo-code:

std::mt19937 gen(someSeed);
std::uniform_int_distribution<int> dis(-9, 9);
int myNumber = dis(gen)
like image 20
KillianDS Avatar answered Nov 07 '22 14:11

KillianDS


Your code returns number between (0-9 and 17-9) = (-9 and 8).

For your information

 rand() % N;

returns number between 0 and N-1 :)

The right code is

rand() % 19 + (-9);
like image 7
Davide Aversa Avatar answered Nov 07 '22 15:11

Davide Aversa


You are right in that there are 18 counting numbers between -9 and 9 (inclusive).

But the computer uses integers (the Z set) which includes zero, which makes it 19 numbers.

Minimum ratio you get from rand() over RAND_MAX is 0, so you need to subtract 9 to get to -9.

The information below is deprecated. It is not in manpages aymore. I also recommend using modern C++ for this task.

Also, manpage for the rand function quotes:

"If you want to generate a random integer between 1 and 10, you should always do it by using high-order bits, as in

j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));

and never by anything resembling

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

(which uses lower-order bits)."

So in your case this would be:

int n= -9+ int((2* 9+ 1)* 1.* rand()/ (RAND_MAX+ 1.));
like image 3
nurettin Avatar answered Nov 07 '22 14:11

nurettin