return random variables within array depending on logic variable or resample variable in scipy

StackOverflow https://stackoverflow.com/questions/14839107

  •  09-03-2022
  •  | 
  •  

Question

I've tried searching for one of these answers quite a bit, and can't find what I'm looking for. I'm sure it's fairly basic and I either don't know how to phrase the search for what i'm looking for, am going about it the wrong way.

Using scipy I would like to either:

define a variable by a random distribution and have it return a new value each time it is called, for example:

x = np.random.normal(30,30/10)
x = #random number
x = #new random number

the end goal is to get this bit of code (and several more like it) to return random variables for numbers for g1 and g2 defined by their distribution for each location within the array gamma. I'd be happy to look up the random values within g1rand and g2rand if that would work, but I haven't been able to figure out how to populate the gamma array with a loop for that either. The eventual goal is to run MC simulations of the code. Thanks in advance.

disc = 11j #number of intervals
depth = 50
q = 300 #number of random sampls
n = depth
interval_thickness =abs(n/(abs(disc)-1))
depth_array = np.r_[0:n:(disc)]
ld1 = 10.0
ld2 = 70.0
g1 = 120
g1rand = np.random.normal(g1,g1/10,q)
g2 = 60
g2rand = np.random.normal(g2,g2/10,q)
condlist = [depth_array <= 0,depth_array<=ld1, depth_array<=ld2]
choicelist = [0, g1, g2]
gamma = np.select(condlist, choicelist)
interval_weight=interval_thickness*gamma
Was it helpful?

Solution

I don't think I fully understand what you are trying to do in your longer piece of code, but if you want to generate your random samples one by one, you could use scipy.stats.norm :

>>> import scipy.stats
>>> x = scipy.stats.norm(loc=30, scale=30/10) # loc is mean, scale is stdev
>>> x.rvs() # return a single random sample from distribution
30.0640285320252
>>> x.rvs()
29.773804986818252
>>> x.rvs(5) # returns an array of 5 random samples from distribution
array([ 31.46684871,  28.5463796 ,  30.37591994,  30.50111085,  32.19189648])
>>> x.mean() # recover distribution parameters from x
30.0
>>> x.std()
3.0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top