2016-04-04 43 views
6

假设我要创建列表或5个元素这样的numpy的阵列创建随机阵列:如何在一定范围内

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

其中:

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

这是一个示例,显示某些范围包含分数。什么是一个简单的方法来做到这一点?

+2

5维或5元? – Divakar

+1

对'np.random'函数做5个适当的调用,并将结果粘贴到一个数组中。 – user2357112

+0

@Divakar 5元素:-D –

回答

10

可以使用numpy.random.uniform只是做(感谢user2357112!)

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

+2

这已经存在;它是['np.random.uniform'](http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.random.uniform.html)。 – user2357112

+0

@ user2357112谢谢!我会更新。 –

+0

[显然中间的3个元素必须是整数。](http://stackoverflow.com/questions/36412006/how-to-create-a-random-array-in-a-certain-range?noredirect=1#评论60440012_36412006) – user2357112

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

print(array) 

打印:

[9.444064187694842, 1.2256912728995506] 

你可能想圆()

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] 

如果你想在一个g o你可以使用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])