Random number that averages a particular number

假如想象 提交于 2020-01-04 04:02:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!