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.
You want (2). This samples a
Geometric Distribution
(link) with meank
.A geometric distribution represents an experiment of this kind:
p
and 0 with probability1-p
So if
X ~ G(p)
, whereX
is a random variable andp
is the probability above, thenX
represents "What is the index of the first event with an outcome of 1?" The expectation isE[X] = 1/p
.Given this information it should now be clear that the following represents a sampling of the random variable
X
withp = 1/k
(and is equivalent to (2)).Be aware that looking at the peak (mode) and expectation of the distribution are not the same thing. The peak of the geometric distribution is always going to be at 1!