问题
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:
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
}
回答2:
This can serve as an alternative for future references which can get the probability of precise values such as 99.999% or 0.0001% To get probability(real percentage) do as such:
//70%
double probability = 0.7;
double result = rand() / RAND_MAX;
if(result < probability)
//do something
I have used this method to create very large percolated grids and it works like a charm for precision values.
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/3572343/how-to-obtain-a-value-based-on-a-certain-probability