Generate a random number sequence to get and average

混江龙づ霸主 提交于 2019-12-06 03:59:38

问题


I am looking to generate a number sequence where each number is between 70 and 100 there will be x numbers in the sequence and it will give and average of y. What would this algorithm look like?


回答1:


I think it is impossible for them to be uniformly distributed between 70 and 100 and have a given average at the same time.

What you can do is generate random numbers that have a given average and then scale them to fit into [70, 100] (but they will not be uniformly distributed there).

  1. generate random numbers [0..1(

  2. calculate their average

  3. multiply all of them to match the required average

  4. if any of them does not fit into [70, 100], scale all of them again by reducing their distance from y by the same factor (this does not change the average). x[i] = y + (x[i] - y)*scale

You will end up with numbers that are all in the range [70, 100(, but they will be uniformly distributed across a different (but overlapping) interval that is centered on y. Also, this approach only works with real/floating-point numbers. If you want integers, you got a combinational problem on your hands.




回答2:


Python example

import random
import time

x     = 10
total = 0
avg   = 0


random.seed(time.time())
for x in range(10):
    total += random.randint(70,100)

avg = total /x

print "total: ", total
print "avg: ", avg



回答3:


        Random r = new Random();
        List<int> l = new List<int>();
        Console.Write("Please enter amount of randoms ");
        int num = (int)Console.Read();
        for (int i = 0; i < num; i++)
        {
            l.Add(r.Next(0, 30) + 70);
        }

        //calculate avg
        int sum = 0;
        foreach (int i in l)
        {
            sum += i;
        }

        Console.Write("The average of " + num + " random numbers is " + (sum / num));

        //to stop the program from closing automatically
        Console.ReadKey();


来源:https://stackoverflow.com/questions/11149051/generate-a-random-number-sequence-to-get-and-average

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