问题描述
我想生成1到10之间的100个随机数。但是这100个随机数的平均值应该是7。我该怎么做?我正在做如下:
//生成随机数
Random random = new Random();
int值= random.Next(1,10);
并将每个值存储在数组中。如果数组中100个项目的平均值不是7,那么我需要再获取100个随机数。有人可以建议一种更好的方法吗?
- 初始化
A [0],...,A [99]
到1
。 - 初始化
I = {0,1,...,99}
。 - 重复步骤4-6 600次。
- 从
I
中均匀地随机选择i
。 - 增量
A [i]
。 - 如果
A [i] == 10
,然后从I
中删除i
。
这将保证 sum(A)
为700,因此 avg(A)
为7。 / p>
但是请注意,这不会在{1,中的所有此类100个整数数组中给出 uniform 分布。 ..,10}的总和为700。设计均匀采样算法将是一项更具挑战性的工作。
I want to generate 100 random numbers between 1 and 10. But the average of those 100 random numbers should be 7. How can I do that? I am doing as follows:
//generating random number
Random random = new Random();
int value = random.Next(1,10);
And storing each value in an array. If the average of 100 items in the array is not 7 then I need to get another 100 random numbers. Can anyone suggest a better way of doing this?
- Initialize
A[0], ..., A[99]
to1
. - Initialize
I = {0, 1, ..., 99}
. - Repeat steps 4-6 600 times.
- Pick random
i
uniformly fromI
. - Increment
A[i]
. - If
A[i] == 10
, then removei
fromI
.
This will guarantee sum(A)
is 700 and thus avg(A)
is 7.
Note however that this does not give a uniform distribution over all such arrays of 100 integers in {1, ..., 10} such that they sum to 700. To devise an algorithm for uniformly sampling would be a much more challenging exercise.
这篇关于固定平均值的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!