vendredi 21 août 2020

Use loop for np.random or reshape array to matrix?

I am new to programming in general, however I am trying really hard for a project to randomy choose some outcomes depending on the proability of that outcome happening for lotteries that i have generated and i would like to use a loop to get random numbers each time.

This is my code:

 import numpy as np
 p = np.arange(0.01, 1, 0.001, dtype = float) 

 alpha = 0.5
 alpha = float(alpha) 
 alpha = np.zeros((1, len(p))) + alpha 

 def w(alpha, p):
     return np.exp(-(-np.log(p))**alpha) 
 w = w(alpha, p)

 def P(w):
     return np.exp(np.log2(w))
 prob_win = P(w)

 prob_lose = 1 - prob_win

 E = 10
 E = float(E) 
 E = np.zeros((1, len(p))) + E
     
 b = 0
 b = float(b) 
 b = np.zeros((1, len(p))) + b

 def A(E, b, prob_win):
     return (E - b * (1 - prob_win)) / prob_win
 a = A(E, b, prob_win)   
 a = a.squeeze() 

 prob_array = (prob_win, prob_lose)
 prob_matrix = np.vstack(prob_array).T.squeeze() 

 outcomes_array = (a, b)
 outcomes_matrix = np.vstack(outcomes_array).T

 outcome_pairs = np.vsplit(outcomes_matrix, len(p))
 outcome_pairs = np.array(outcome_pairs).astype(np.float)

 prob_pairs = np.vsplit(prob_matrix, len(p))
 prob_pairs = np.array(prob_pairs)

 nominalized_prob_pairs = [outcome_pairs / np.sum(outcome_pairs) for 
 outcome_pairs in np.vsplit(prob_pairs, len(p)) ]

The code works fine but I would like to use a loop or something similar for the next line of code as I want to get for each row/ pair of probabilities to get 5 realizations. When i use size = 5 i just get a really long list but I do not know which values still belong to the pairs as when size = 1

 realisations = np.concatenate([np.random.choice(outcome_pairs[i].ravel(), 
 size=1 , p=nominalized_prob_pairs[i].ravel()) for i in range(len(outcome_pairs))])

or if I use size=5 as below how can i match the realizations to the initial probabilities? Do i need to cut the array after every 5th element and then store the values in a matrix with 5 collums and a new row for every 5th elemt of the initial array? if yes how could I do this?

 realisations = np.concatenate([np.random.choice(outcome_pairs[i].ravel(), 
 size=1 , p=nominalized_prob_pairs[i].ravel()) for i in range(len(outcome_pairs))])

Thank you so much for your help in advance




Aucun commentaire:

Enregistrer un commentaire