How to obtain a value based on a certain probability

Manas picture Manas · Aug 26, 2010 · Viewed 7k times · Source

I have some functions which generate double, float, short, long random values. I have another function to which I pass the datatype and which should return a random value. Now I need to choose in that function the return value based on the passed datatype. For example, if I pass float, I need:

the probability that the return is a float is 70%, the probability that the return is a double, short or long is 10% each. I can make calls to the other function for generating the corresponding random values, but how do I fit in the probabilistic weights for the final return? My code is in C++.

Some pointers are appreciated.

Thanks.

Answer

mmonem picture mmonem · Aug 26, 2010

C++ random numbers have uniform distribution. If you need random variables of another distribution you need to base its mathematical formula on uniform distribution.

If you don't have a mathematical formula for your random variable you can do something like this:

int x = rand() % 10;
if (x < 7)
{
 // return float
}
else (if x == 7)
{
 // return double
}
else (if x == 8)
{
 // return short
}
else (if x == 9)
{
 // return long
}