Efficient way for generating N arrays of random numbers between different ranges

I want to generate N arrays of fixed length n of random numbers with numpy, but arrays must have numbers varying between different ranges.

So for example, I want to generate N=100 arrays of size n=5 and each array must have its numbers between:

  • First number between 0 and 10
  • Second number between 20 and 100

and so on...

First idea that comes to my mind is doing something like:

first=np.random.randint(0,11, 100) 
second=np.random.randint(20,101, 100)
...

And then I should nest them, Is there a more efficient way?

2 answers

  • answered 2017-06-17 19:27 Fran Roura

    I would just put them inside another array and iterate them through their index

    from np.random import randint
    array_holder = [[] for i in range(N)] # Get N arrays in a holder
    ab_holder = [[a1, b1], [a2, b2]]
    for i in range(len(array_holder)): # You iterate over each array
        [a, b] = [ab_holder[i][0], ab_holder[i][1]]
        for j in range(size): # Size is the ammount of elements you want in each array
            array_holder[i].append(randint(a, b)) # Where a is your base and b ends the range
    

  • answered 2017-06-17 19:27 Bill Bell

    Another possibility. Setting ranges indicates both what the ranges of the individual parts of each arrays must be and how many there are. size is the number of values to sample in each individual part of an array. N is the size of the Monte-Carlo sample. arrays is the result.

    import numpy as np
    
    ranges = [ (0, 10), (20, 100) ]
    size = 5
    N = 100
    
    arrays = [ ]
    for n in range(N):
        one_array = []
        for r in ranges:
            chunk = np.random.randint(*r, size=size)
            one_array.append(chunk)
        arrays.append(one_array)
    

    It might make an appreciable difference to use numpy's append in place of Python's but I've written this in this way to make it easier to read (and to write :)).