假设我有一个数字,例如 100,我想生成 5 个不同的随机数,但它们的总和必须为 100,我该怎么做? (最好是在 PHP 中。对于数学向导/统计学家,我不需要真正的随机数,而是看起来随机的东西)。
所以这个函数会产生这样的结果:
5、51、9、18、19 = 100 34、52、3、7、4 =100
等等。
理想情况下,需要 5、100 并产生其余部分:
生成随机数(100,5)
最佳答案
a = RandomInteger[{1, 96}]
b = RandomInteger[{1, 97 - a}]
c = RandomInteger[{1, 98 - a - b}]
d = RandomInteger[{1, 99 - a - b - c}]
e = 100 - a - b - c - d
示例:
{34,25,26,3,12,Sum =,100}
{90,5,1,1,3,Sum =,100}
{29,16,21,9,25,Sum =,100}
{4,13,71,10,2,Sum =,100}
当然,这些数字并不是均匀分布的。
编辑
这是一个更均匀的分布:
a = RandomInteger[{1, 20}];
b = RandomInteger[{1, 40 - a}];
c = RandomInteger[{1, 60 - a - b}];
d = RandomInteger[{1, 80 - a - b - c}];
e = 100 - a - b - c - d;
输出:
{5,33,2,8,52,Sum =,100}
{14,9,50,5,22,Sum =,100}
{3,23,12,34,28,Sum =,100}
{1,16,4,5,74,Sum =,100}
{6,28,6,9,51,Sum =,100}
{11,25,7,1,56,Sum =,100}
{4,34,12,18,32,Sum =,100}
{6,13,25,26,30,Sum =,100}
{8,27,14,5,46,Sum =,100}
{17,13,23,25,22,Sum =,100}
以下是数字的频率:
编辑
也许更好:
a = Max[#, 1] & /@ Evaluate[RandomInteger[{1, 20}, 5] - 1];
b = 100 - Total@a;
c = Mod[b, 5];
d = (b - c)/ 5;
a = a + d + {c, 0, 0, 0, 0};
分布:
编辑
在 Mathematica您可以轻松生成加起来为 100 的所有 5 元组:
IntegerPartitions[100, {5}]
不计排列,共有 38225 种不同的野兽
Length@IntegerPartitions[100, {5}]
(* -> 38225 *)
这些五元组中每个数字的频率是:
Histogram@Flatten@IntegerPartitions[100, {5}]
如果考虑排列,曲线非常相似:
t = Tally@Flatten@(Permutations[#] & /@ IntegerPartitions[100, {5}]);
ListLinePlot@SortBy[t, #[[1]] &][[All, 2]]
关于php - 参数内的 n 个随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4261858/