views:

55

answers:

3

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.

+1  A: 

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
}
mmonem
@mmonem You make an interesting point. I think a mathematical formula based on some probability distribution is what I would eventually like to do. There are some other variables involved, which I didn't mention in my question for reasons of simplicity. But for the time being, your solution is just what I needed. Thanks!
Manas
A: 

I do not know if I understand correctly what you want to do, but if you just want to assure that the probabilities are 70-10-10-10, do the following:

  • generate a random number r in (1,2,3,4,5,6,7,8,9,10)
  • if r <= 7: float
  • if r == 8: short
  • if r == 9: double
  • if r == 10: long

I think you recognize and can adapt the pattern to arbitrary probability values.

phimuemue
@phimuemue, I adapted your and @mmomen's solution to fit my requirements. Unfortunately I can only mark one reply as the accepted answer. Thanks for the pointer.
Manas
+1  A: 

mmonem has a nice probabilistic switch, but returning different types isn't trivial either. You need a single type that may adequately (for your purposes) encode any of the values - check out boost::any, boost::variant, union, or convert to the most capable type (probably double), or a string representation.

Tony
I presume @Manas is focusing on the the probabilistic issue as the title of the question suggests and what the question ends with; *'how do I fit in the probabilistic weights for the final return?'*
mmonem
But @Manas also doesn't seem to get the difficulties with the return value.
Elemental
@Tony, The global random generator function returns a _variant_t. That takes care of the return value being of different datatypes (double, float, short, long). Nonetheless, "boost::any" does sound interesting. I think I'll take a look at that just out of curiosity. Thanks for the pointer.
Manas