pythonnumpyrandomuniform

How to randomly generate random numbers in one of two intervals in Python


I want to generate random numbers from two different ranges [0, 0.3) and [0.7, 1) in python.

numpy.random.uniform has the option of generating only from one particular interval.


Solution

  • How about this one?

    first_interval = np.array([0, 0.3])
    second_interval = np.array([0.7, 1])
    
    total_length = np.ptp(first_interval)+np.ptp(second_interval)
    n = 100
    numbers = np.random.random(n)*total_length
    numbers += first_interval.min()
    numbers[numbers > first_interval.max()] += second_interval.min()-first_interval.max()