Skip to content Skip to sidebar Skip to footer

How To Use Numpy To Generate Random Numbers On Segmentation Intervals

I am using numpy module in python to generate random numbers. When I need to generate random numbers in a continuous interval such as [a,b], I will use (b-a)*np.random.rand(1)+a

Solution 1:

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])

Solution 2:

You can use

np.random.uniform(a,b)

for your random numbers between a and b (including a but excluding b)

So for random number in [a,b] and [c,d], you can use

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

Solution 3:

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.

Solution 4:

You can just assign a probability for how likely it will be [a,b] or [c,d] and then generate accordingly:

import numpy as np
import random

random_roll = random.random()
a = 1
b = 5
c = 7
d = 10if 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)

Post a Comment for "How To Use Numpy To Generate Random Numbers On Segmentation Intervals"