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

问题描述 投票:5回答:3

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

algorithm random numbers
3个回答
2
投票

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

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

  1. 生成随机数[0..1(
  2. 计算他们的平均值
  3. 将所有这些乘以匹配所需的平均值
  4. 如果它们中的任何一个不适合[70,100],则通过将它们与y的距离减少相同因子再次缩放所有这些(这不会改变平均值)。 x[i] = y + (x[i] - y)*scale

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


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

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();
© www.soinside.com 2019 - 2024. All rights reserved.