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?
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], ab_holder[i]] 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
Another possibility. Setting
rangesindicates both what the ranges of the individual parts of each arrays must be and how many there are.
sizeis the number of values to sample in each individual part of an array.
Nis the size of the Monte-Carlo sample.
arraysis 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
appendin place of Python's but I've written this in this way to make it easier to read (and to write :)).