I need code to generate a random number between -95 and 95. The code I'm currently using is seeded with the time, so when I call it over and over again rapidly, my cube (part of a game I'm working on) goes left to right, then starts over. Could someone please provide me with code that reliably creates a random number between -95 and 95? Thanks.

My Code:

void movecube(){
	srand ( time(NULL) );
	e = rand() % 95 + -95;
	f = rand() % 95 + -95;
}

To generate a number within a specified range (i.e. -95 to 95, inclusive), you need to take a random number modulo the range. If the highest number in the range must be included, you take the modulo (range+1).

Once you have taken the modulus of the random number, you add the minimum value of the range to the result.

srand((unsigned)time(NULL));

const int MIN = /*provide a min*/;
const int MAX = /*provide a max*/;
const int RANGE = (MAX - MIN);

int aNumber = (rand()%(RANGE+1) + MIN);

This is the general algorithm for generating numbers in the range [MIN, MAX], you will have to modify it to fit different situations (i.e. [MIN, MAX) or (MIN, MAX))

You should also only seed the random number generator once early in the lifecycle of the program. time() measures seconds, so if you seed twice in the same second, the generated numbers will be the same.

Using rand() % n for a random number between 0 and n-1 gives results that are generally not random, even if rand() itself is perfect.

To see why, assume that rand() returns a 32-bit signed value, i.e. a value between 0 and 2147483647, inclusive, and that you are computing rand() % 190.

There are 2147483648 possible values that rand() can take on, and 2147483648 % 190 is 98. In other words, 190 does not divide 2147483648 exactly. This fact means that the 190 possible values that this algorithm yields cannot possibly occur with equal probability.

Having pointed out the problem, I'm going to leave the solution as an exercise...or, if you like, you can look up the nrand function in Accelerated C++.

Edited 6 Years Ago by arkoenig: n/a

This question has already been answered. Start a new discussion instead.