生成随机数序列以获得和平均

时间:2012-06-22 01:16:02

标签: algorithm random numbers

我希望生成一个数字序列,其中每个数字在70到100之间,序列中将有x个数字,它将给出y的平均值。这个算法会是什么样的?

3 个答案:

答案 0 :(得分:2)

我认为它们不可能在70到100之间均匀分布,并且同时具有给定的平均值。

你可以做的是生成具有给定平均值的随机数,然后将它们缩放以适合[70,100](但它们不会在那里均匀分布)。

  1. 生成随机数[0..1(

  2. 计算他们的平均值

  3. 将所有这些数字相乘以匹配所需的平均值

  4. 如果它们中的任何一个不适合[70,100],则通过将它们与y的距离减少相同的因子(这不会改变平均值)再次缩放所有这些。 x[i] = y + (x[i] - y)*scale

  5. 你最终得到的数字都在[70,100范围内(但是它们将均匀分布在以y为中心的不同(但重叠)的区间内。此外,这种方法仅适用于真实/浮点数。如果你想要整数,你就会遇到一个组合问题。

答案 1 :(得分:0)

Python示例

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

答案 2 :(得分:0)

        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();
相关问题