int Prob (int num)
{int Cnc;
Cnc=(rand() % MAX)+1;
if (Cnc <= num)
{return 1;}
else
{return 0;}}
When MAX is 10000 and num is 5000, the experimental probability of the function returning 1 is almost always between 0.55 and 0.53, even though it should be very close to 0.5 when one trial consists of running it 10000 times. I really don't understand why this is happening. I probably won't be using the function enough for it to actually make a difference, but it still bothers me for some reason. Any help would be appreciated.
I see what the problem is, your OS must be Windows (otherwise how would you compile "void main"?), and RAND_MAX there is only 32767.
Instead of rand() % MAX, try (double)rand() / RAND_MAX * MAX or C++ random number machinery (std::uniform_int_distribution etc)
If you are are using Visual C++ RAND_MAX is 32767.
There are 3*5000 values of rand() in the range 1-30000 that will make Prob return 1, plus 2768 values in the range 30001-32768. That makes a total of 17768 values of 32768 possible. 17768/32768 ≈ 54%
The problem is the values in the range 30001-32768. What you can do to fix this is to not use values in that range. Just keep generate random numbers until you get a number in the range 1-30000.
1 2 3 4 5
int Cnc;
do
{
Cnc=(rand() % MAX)+1;
} while (Cnc > RAND_MAX - RAND_MAX % (2*num));