Binomial distribution to return an Numpy array

4.8k Views Asked by At

Need to Generate a binomial distribution, tested 10 times, given the number of trials(n) and probability(p) of each trial.

The output should contain a numpy array with 10 numbers representing the required binomial distribution.

Sample Input: 0 10 0.5

Expected Output:

[5 6 5 5 5 6 5 7 8 5]

My Code:

import numpy as np
import pandas as pd
pd.set_option('display.max_columns', 500)
np.random.seed(0)
seed=int(input())
n=int(input())
p=float(input())
i = 1
while i <= n:
    x = np.random.binomial(n, p)
    s=np.array(x)
    print(s)
    i += 1

Code Output:

5 6 5 5 5 6 5 7 8 5

Output is not coming out as desired what am i doing wrong here?

4

There are 4 best solutions below

3
Reza On

Try this which generates 10 binomial RVs without a loop:

import numpy as np
n = 8
p = 0.1
np.random.seed(0)
s = np.random.binomial(n, p, 10)
print(s)
# array([0, 1, 2, 0, 2, 0, 2, 0, 3, 0])
0
Varun Kotian On

try this,

np.random.seed(0)
s=np.random.binomial(n,p,10)
print(s)
2
jelly_s On
import numpy as np 

seed=int(input())
n=int(input())
p=float(input())

np.random.seed(seed)
s =np.random.binomial(n, p, 10)
print(s)
0
Imam_AI On

Keeping the original input value, please find the code below:

import numpy as np
import pandas as pd
pd.set_option('display.max_columns', 500)
np.random.seed(0)
seed=int(input())
n=int(input())
p=float(input())
# Above code has been taken from the original requester as using the above input 
# output will be generated
npr = 10
np.random.seed(seed) 
s = np.random.binomial(n, p, npr)
print(s)