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

Cle*_*lee 7 python arrays random numpy numpy-random

假设我想创建一个包含5个元素的列表或numpy数组,如下所示:

array = [i, j, k, l, m] 
Run Code Online (Sandbox Code Playgroud)

哪里:

  • i 在1.5到12.4的范围内
  • j 在0到5的范围内
  • k 在4到16的范围内
  • l 在3到5的范围内
  • m 在2.4到8.9的范围内.

这是一个示例,表明某些范围包括分数.什么是一个简单的方法来做到这一点?

Ami*_*ory 10

你可以做(​​感谢user2357112!)

[np.random.uniform(1.5, 12.4), np.random.uniform(0, 5), ...]
Run Code Online (Sandbox Code Playgroud)

使用numpy.random.uniform.

  • 这已经存在; 它是[`np.random.uniform`](http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.random.uniform.html). (2认同)

MSe*_*ert 6

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

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]
Run Code Online (Sandbox Code Playgroud)

如果你想一次性创建它们,你可以使用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])
Run Code Online (Sandbox Code Playgroud)