简体   繁体   English

使用 Numpy 生成范围内的随机数

[英]Generate Random Number within range using Numpy

I have ranges , where each tuple represents the range of a random number.我有ranges ,其中每个元组代表一个随机数的范围。 eg:例如:

ranges = [(-1,100), (0,1), (50, 5000)]

Now, I want to create a numpy array where each element of array is randomly generated from the corresponding tuple of ranges .现在,我想创建一个 numpy 数组,其中数组的每个元素都是从相应的ranges元组中随机生成的。

Pseudo code:伪代码:

rand_array = numpy.array[randomly generate element1 from (-1,100), randomly generate element2 from (0,1), randomly generate element3 from (50,500)]

Of course, naive way to do this is:当然,天真的方法是:

rand_array = [random.uniform(coord[0], coord[1]) for coord in ranges]

But I want to do it in numpy way, as my whole code accepts numpy array data-types.但我想以 numpy 的方式来做,因为我的整个代码都接受 numpy 数组数据类型。 Another solution can be to convert naively generated rand_array to numpy array.另一种解决方案是将天真生成的rand_array转换为numpy数组。 But I think it is not efficient.但我认为效率不高。 Is there a numpy way of doing this?有这样做的 numpy 方式吗?

Most random functions accept array parameters.大多数随机函数接受数组参数。 So you can do所以你可以做

np.random.uniform(*np.transpose(ranges))

The usual broadcasting rules apply, for example, to get 10 triplets例如,通常的广播规则适用于获得 10 个三胞胎

np.random.uniform(*np.transpose(ranges),(10,3))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM