I came across the following question:
Using rand() function, generate a number with expected value k. Options are:
1)
int GetRandom(int k)
{
v=0;
while(rand()<1.0f/(float)k)
v++;
return v;
}
2)
int GetRandom(int k)
{
v=0;
while(rand()<(1-1.0f/(float)k))
v++;
return v;
}
3)
int GetRandom(int k)
{
v=0;
while(rand() > (1-1.0f/(float)(k+1)))
v++;
return v;
}
1) seemed like the correct answer. Examining the outcome for specific values of k
seems to indicate this is the not the case. (I set k=3
. The frequency distribution of values for 100000
trials can be seen in the image below )
How would one do this ?
The question is somewhat similar to this one.