jeudi 19 avril 2018

Generating a random array with additional constraints

I'm trying to generate a numpy array of random values, satisfying some additional constraints, and for a given fixed length N. Is it better to:

Make a list (sampling once at a time), then convert it to a numpy array

while len(list)<N:
    num=np.random.rand(1)
    if num <.5:
        list.append(np.random.rand(1))
x=np.array(list)

Use vectorized code, and append to the array:

x=np.array([])
while x.shape[0]<N:
    x=np.append(x,np.random.rand(int(N/2))
    x=x[x<.5][:N]

Overshoot the array length, then try until the masked version is long enough

x=np.array([])
while x.shape[0]<N:
    x=np.random.rand(4*N)
    x=x[x<.5][:N]




Aucun commentaire:

Enregistrer un commentaire