我正在尝试创建一个由 0.005 到 0.045 之间的 N 个随机数组成的列表(称为:权重),总和等于 1。N 可以是 22 到 200 之间的任何整数。因此有以下限制:
- 权重中的数字个数 = N
- 对于权重中的每个 n:0.005 < n < 0.045
- 权重中所有 n 的总和 = 1
我认为第一个限制很简单。另外,我知道如何分别修复第二个和第三个限制。但我不知道如何将它们组合成一段代码。
- 第二个限制:0.005 < x < 0.045:
import numpy as np
import random
weights_step1 = np.random.randint(min=5, max = 45, size = N)
weights = []
for weight in weights_step1:
weights.append(weight/1000)
- 第三个限制
Generating a list of random numbers, summing to 1
有谁知道如何将这两种限制纳入一段代码中?
最佳答案
您可能想使用Dirichlet Rescale algorithm (DRS) ,其中 Python implementation可用:
这为您提供了适当的统计保证。引用数学论文的摘要:
the vectors are uniformly distributed over the valid region of the domain of all possible vectors, bounded by the constraints.
尝试 50 个数字的总和为 1:
$ pip install drs
...
Installing collected packages: drs
Successfully installed drs-2.0.0
$
$ python3
Python 3.9.9 (main, Nov 19 2021, 00:00:00)
...
>>>
>>> from drs import drs
>>>
>>> n = 50
>>> s = 1.0
>>>
>>> v1 = drs(n, s, n*[0.045], n*[0.005])
>>> sum(v1)
1.0000000000000004
>>> max(v1)
0.04278387127251347
>>> min(v1)
0.005035400173241331
>>>
>>> v2 = drs(n, s, n*[0.045], n*[0.005])
>>> sum(v2)
0.9999999999999994
>>> max(v2)
0.04445793844097045
>>> min(v2)
0.005294943276519565
>>>
关于python - 创建一个包含 N 个随机数的列表,其中包含最大值、最小值和总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70593981/