# Thread: RAND() Does it favor the lower number?

1. ## RAND() Does it favor the lower number?

I thought so once. I had created a simulation where creatures live in my artifisial enviorment as is they, move around, eat, reproduce, and die. Now, I used RAND() to detirmain the random locations of the food, creatures and sex of the creatures. And I noticed that most of the creatures where female. In my code 1 ment a male, and 0 meant a female. Also most of the creatures and food seemed to allways popup near the x-y coords of 0x0. (Near the top left.) So I threw together a program that checked the average. Here is my code:

Code:
```#include <windows.h>
#define MAX_TIMES 500000
int WINAPI WinMain (HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
LPSTR lpszArgument,
int nFunsterStil)
{
char szText[MAX_PATH * 10];
strcpy(szText, "This program will run the RAND() function\nthrough a loop, then display the average.");
MessageBox(NULL, szText, "Random Generator Tester", MB_ICONINFORMATION);
int nRand[MAX_TIMES];
int nResualt;
for(int i = 0; i < MAX_TIMES; i++){
nRand[i] = rand()%1000;
nResualt += nRand[i];  }
nResualt /= MAX_TIMES;
wsprintf(szText, "After running RAND() five hundred thousand times at\nthe value of 1000, the average has been gauged at %d.", nResualt);
MessageBox(NULL, szText, "Random Generator Tester", MB_ICONINFORMATION);
return 0;
}```
Amazingly, the result is 496. So it does favor the lower number a tiny bit, but I expected more so than this.

2. void srand(unsigned int seed);

3. Using modulo to restrict the range of random numbers generated throws out the higher order bits. This is explained in the FAQ about two-thirds of the way down the page. There is also a suggestion as to how to avoid that problem. Unfortunately we are still dealing with random numbers (actually pseudo-random) and though in the long term one would expect an even distribution of values and therefore a statistical average approaching the mid point of the range, there would still be the chance for this average to not be near the mid-point (the greater the sample the closer to the middle the average should turn out). Issues of the distribution are also addressed in the FAQ article mentioned.

4. You could do some bit transposing before taking modular residues to mask this discrepancy; or use some other "more random" generator, like Mersenne Twister or ISAAC. (I'd recommend MT.)

Or declare it a program "feature" and tell your users this is all part of the challenge

5. There is an extensive discussion about this here: http://eternallyconfuzzled.com/articles/rand.html

Popular pages Recent additions