如何在一定范围内创建随机数组

How to create a random array in a certain range

假设我想像这样创建一个包含 5 个元素的列表或 numpy 数组:

array = [i, j, k, l, m] 

其中:

这是一个显示某些范围包含分数的示例。执行此操作的简单方法是什么?

你可以做到(感谢user2357112!)

[np.random.uniform(1.5, 12.4), np.random.uniform(0, 5), ...]

使用 numpy.random.uniform.

import random
array = [random.uniform(1.5, 12.4), random.uniform(0,5)]

print(array)

打印:

[9.444064187694842, 1.2256912728995506]

你可能想用 round()

将它们四舍五入

我建议手动生成它们并稍后创建列表:

import numpy as np
i = np.random.uniform(1.5, 12.4)
j = np.random.randint(0, 5)  # 5 not included use (0, 6) if 5 should be possible
k = np.random.randint(4, 16) # dito
l = np.random.randint(3, 5)  # dito
m = np.random.uniform(2.4, 8.9.)

array = np.array([i, j, k, l, m]) # as numpy array
# array([  3.33114735,   3.        ,  14.        ,   4.        ,   4.80649945])

array = [i, j, k, l, m]           # or as list
# [3.33114735, 3, 14, 4, 4.80649945]

如果您想一次性创建它们,您可以使用 np.random.random 使用范围和下限修改它们并将它们转换为不需要浮点数的整数:

# Generate 5 random numbers between 0 and 1
rand_numbers = np.random.random(5) 

# Lower limit and the range of the values:
lowerlimit = np.array([1.5, 0, 4, 3, 2.4])
dynamicrange = np.array([12.4-1.5, 5-0, 16-4, 5-3, 8.9-2.4]) # upper limit - lower limit

# Apply the range
result = rand_numbers * dynamicrange + lowerlimit

# convert second, third and forth element to integer
result[1:4] = np.floor(result[1:4]) 

print(result)
# array([ 12.32799347,   1.        ,  13.        ,   4.        ,   7.19487119])