简体   繁体   English

如何使用numpy在分段间隔上生成随机数

[英]How to use numpy to generate random numbers on segmentation intervals

I am using numpy module in python to generate random numbers. 我在python中使用numpy模块生成随机数。 When I need to generate random numbers in a continuous interval such as [a,b], I will use 当我需要以连续间隔(例如[a,b])生成随机数时,我将使用

(b-a)*np.random.rand(1)+a

but now I Need to generate a uniform random number in the interval [a, b] and [c, d], what should I do? 但是现在我需要在[a,b]和[c,d]区间生成一个统一的随机数,该怎么办?

I want to generate a random number that is uniform over the length of all the intervals. 我想生成一个随机数,该随机数在所有时间间隔的长度上是统一的。 I do not select an interval with equal probability, and then generate a random number inside the interval. 我没有以相等的概率选择一个间隔,然后在该间隔内生成一个随机数。 If [a, b] and [c, d] are equal in length, There is no problem with this use, but when the lengths of the intervals are not equal, the random numbers generated by this method are not completely uniform. 如果[a,b]和[c,d]的长度相等,则这种使用没有问题,但是当间隔的长度不相等时,由该方法产生的随机数不是完全均匀的。

You could do something like 你可以做类似的事情

a,b,c,d = 1,2,7,9
N = 10
r = np.random.uniform(a-b,d-c,N)
r += np.where(r<0,b,c)
r
# array([7.30557415, 7.42185479, 1.48986144, 7.95916547, 1.30422703,
#        8.79749665, 8.19329762, 8.72669862, 1.88426196, 8.33789181])

You can use 您可以使用

np.random.uniform(a,b)

for your random numbers between a and b (including a but excluding b) 您在a和b之间的随机数(包括a但不包括b)

So for random number in [a,b] and [c,d], you can use 因此,对于[a,b]和[c,d]中的随机数,您可以使用

np.random.choice( [np.random.uniform(a,b) , np.random.uniform(c,d)] )

Here's a recipe: 这是一个食谱:

def random_multiinterval(*intervals, shape=(1,)):
    # FIXME assert intervals are valid and non-overlapping
    size = sum(i[1] - i[0] for i in intervals)
    v = size * np.random.rand(*shape)
    res = np.zeros_like(v)
    for i in intervals:
        res += (0 < v) * (v < (i[1] - i[0])) * (i[0] + v)
        v -= i[1] - i[0]
    return res

In [11]: random_multiinterval((1, 2), (3, 4))
Out[11]: array([1.34391171])

In [12]: random_multiinterval((1, 2), (3, 4), shape=(3, 3))
Out[12]:
array([[1.42936024, 3.30961893, 1.01379663],
       [3.19310627, 1.05386192, 1.11334538],
       [3.2837065 , 1.89239373, 3.35785566]])

Note: This is uniformly distributed over N (non-overlapping) intervals, even if they have different sizes. 注意:即使它们的大小不同,它也会均匀分布在N个(不重叠)的间隔中。

You can just assign a probability for how likely it will be [a,b] or [c,d] and then generate accordingly: 您可以只分配一个概率以[a,b]或[c,d]的可能性为准,然后相应地生成:

import numpy as np
import random

random_roll = random.random()
a = 1
b = 5
c = 7
d = 10
if random_roll > .5: # half the time we will use [a,b]
    my_num = (b - a) * np.random.rand(1) + a
else: # the other half we will use [c,d]
    my_num = (d - c) * np.random.rand(1) + c
print(my_num)

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

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