Home > other >  List of specific number from an uniform distribution, Python
List of specific number from an uniform distribution, Python

Time:12-07

Here is a code that goes over numbers from a given uniform distribution y, and prints the number of values which are less than 1

import numpy as np

y = np.random.uniform(0, 500, 500)

X = 0 # X number of y values < 1

for i in range(0,500):
  if y[i] < 1:
     X  = 1

I would like to be able to repeat this process N times, then store each N values of these X. I tried nesting the for-loop structure inside another for-loop but I could not get it to work. As in

X = 0 # X number of y values < 1
N = 5

for k in range(N):
 for i in range(0,500):
  if y[i] < 1:
     X  = 1
print(X)

CodePudding user response:

You can do this without a loop.

For one number, you can find the total like this:

sum([1 for i in y if i < 1])

If you want five numbers,

samples = []
for _ in range(N):
    y = np.random.uniform(0, 500, 500)
    samples.append(sum([1 for i in y if i < 1]))

You then have the five results in a list.

CodePudding user response:

Your approach will work, and you were very close. You want one outer loop to create the N samples of random of numbers y and one inner loop to count the number of y's that are less than 1 for each sample. However every time you run the inner loop I think that you want to reset your counter X to 0, and to generate a new sample set of random numbers y.


for k in range(N):
 X=0
 y = np.random.uniform(0, 500, 500)
 for i in range(0,500):
  if y[i] < 1:
     X  = 1
 print(X)
  • Related