问题
Seems simple, but I'd like a formula (.net preferably) which:
For a given number- say, 1.5 - the formula will output a random number which taken over a series will average around 1.5... so it could be 0.1, 1.2, 7.1, 2.5, .2, etc, but the average value will be close to 1.5.
clarification: I would like the numbers to be positive.
回答1:
public class RandomAroundAverage
{
Random r = new Random();
public double Random(double middle, double scale)
{
return r.NextDouble() * scale - (scale / 2) + middle;
}
}
then
var v = r.Random(1.5, 20);
and it will generate random numbers -8.5 -> 11.5
and to see it in action...
var r = new RandomAroundAverage();
var sum = 0.0;
for (int i = 0; i < 10000; i++)
{
var v = r.Random(1.5, 20);
sum += v;
Console.WriteLine(string.Format("Value: {0} Average: {1}", v, sum/i));
}
回答2:
There are lots of possible ways to do it. One of these, which is always positive, is to generate exponentially distributed values. An algorithm to generate exponential random variates with a specified mean is:
public static double ExpRV(double mean, Random rnd) {
return -mean * Math.Log(rnd.NextDouble());
}
[Editor's note: Converted to C#.]
When you crank out a bunch of those, the average should be fairly close to mean.
If you need a bounded range for the individual values you'll need a different distribution, but since you didn't specify that as a constraint this should do it for you.
回答3:
I think you have three parameters, numPoints, targetAvg, and maxDist from targetAvg.
Pick numPoints points at random in the range (2, 2*maxDist).
Calculate the avg.
Shift by adding targetAvg-avg to every point.
That will give you points around your target average which average to exactly your target (as close as floating point math allows for).
来源:https://stackoverflow.com/questions/17558281/random-number-that-averages-a-particular-number