Danny
Danny

Reputation: 9634

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?

Upvotes: 22

Views: 58322

Answers (5)

nurettin
nurettin

Reputation: 11736

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.));

Upvotes: 3

Petruza
Petruza

Reputation: 12276

Anytime you have doubts, you can run a loop that gets 100 million random numbers with your original algorithm, get the lowest and highest values and see what happens.

Upvotes: 0

KillianDS
KillianDS

Reputation: 17186

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)

Upvotes: 9

NPE
NPE

Reputation: 500495

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.

Upvotes: 38

Davide Aversa
Davide Aversa

Reputation: 5988

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);

Upvotes: 7

Related Questions