1

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?

user10528004
  • 35
  • 1
  • 2
  • 7

4 Answers4

3

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])
Manoj Kumar
  • 5,273
  • 1
  • 26
  • 33
Reza
  • 1,945
  • 1
  • 9
  • 17
  • i get the following output which is not what i want [5 6 5 5 5 6 5 7 8 5] [6 5 5 7 3 3 2 7 6 7] [8 6 5 6 3 6 3 7 5 5] [4 6 5 5 2 5 5 5 7 6] [4 5 6 3 6 6 4 3 4 4] [5 5 8 3 4 3 6 4 5 4] [3 3 6 3 4 4 6 3 7 3] [8 5 8 5 6 2 4 3 4 3] [4 5 3 6 5 4 5 3 5 7] [4 6 3 6 4 4 5 2 7 1] – user10528004 Sep 08 '20 at 16:52
  • @user10528004 Have you run this code as-is, outside of any loop? – Anakhand Sep 08 '20 at 16:56
  • you need to use it without a loop, it gives you 10 RVs, you don't need a loop – Reza Sep 08 '20 at 17:00
1

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)
Imam_AI
  • 151
  • 1
  • 7
0

try this,

np.random.seed(0)
s=np.random.binomial(n,p,10)
print(s)
0
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)
jelly_s
  • 1
  • 1