python - 创建一个包含 N 个随机数的列表,其中包含最大值、最小值和总和

标签 python list numpy random sum

我正在尝试创建一个由 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/

相关文章:

java - 使用数组实现列表

c# - 查找两个列表中的差异

C++成员初始化列表完整性

python - 使用 Python 替换多个文件中的多个字符串

Python对SQL数据进行分组

python-3.x - 如何在没有 for 循环的情况下调用 numpy 函数列表?

python - 在某些索引中更改 numpy.array 中的字符串值

python - 如何从内存中解码jpg图像?

python - 跨多个轴的点积

python - 创建为日志消息添加前缀的记录器