Reputation: 21
Simulate a random experiment of tossing a coin 10000 times and determine the count of Heads.
Hint: Define a binomial distribution with n = 1
and p = 0.5
.
Use binom function from scipy.stats.
Set the random seed to 1
.
Draw a sample of 10000
elements from defined distribution.
Assume the values 0
and 1
represent Heads and Tails respectively.
Count the number of heads and display it. Make used of bincount
method, available in numpy
.
I found an answer to it but it was not from the scipy.stats
package as asked, it was from random package. Below is my attempt but the answer is not as expected. Kindly help me correct my mistake.
import scipy as sp
from scipy import stats
import numpy as np
import random
from scipy.stats import binom
data_binom = binom.rvs(n=1,p=0.5,size=10000)
np.random.seed(1)
#print(data_binom)
y = np.bincount(data_binom)
head = print(y[0])
print(head)
Upvotes: 2
Views: 7466
Reputation: 4243
set binom.rvs size=1 and then set the probability for heads to be .5
from scipy.stats import binom
flips=binom.rvs(1000,0.5,size=1)
print(flips)
plt.pie([flips,1000])
plt.legend(['heads','tails'])
plt.show()
Upvotes: 0
Reputation: 3633
from scipy.stats import binom
import numpy as np
b = binom(n=1,p=0.5)
np.random.seed(1)
sample = b.rvs(size=10000)
print(np.count_nonzero(sample==0)) # heads is assumed to be zero
This code will work in your environment. Trust me!
Upvotes: 1
Reputation: 41
Seems like the issue is with where you are setting up the seed. Currently you are doing it post your sample selection which should ideally be done before as shown below :
import scipy as sp
from scipy import stats
import numpy as np
from scipy.stats import binom
np.random.seed(1)
data_binom = binom.rvs(n=1,p=0.5,size=10000)
#print(data_binom)
y = np.bincount(data_binom)
head = print(y[0])
print(head)
Guess this is what your expected output is. Cheers!!
Upvotes: 4
Reputation: 692
I got what I expected. Don't know which one is head: 4995 or 5005?
print(y[0])
print(y[1])
4995
5005
Here is more code to explain your tossing:
from scipy.stats import binom
data_binom = binom.rvs(n=1,p=0.5,size=10000)
heads = 0
tails = 0
edges = 0
count = 0
for coin in data_binom:
count += 1
if coin == 1:
heads += 1
elif coin == 0:
tails += 1
else:
edges += 1
print("Observed " + str(count) + " of coin tossing with heads " + str(heads)
+ ", tails " + str(tails) + ", and edges " + str(edges))
Results of four tests:
$ python3.7 test.py
Observed 10000 of coin tossing with heads 4989, tails 5011, and edges 0
$ python3.7 test.py
Observed 10000 of coin tossing with heads 5109, tails 4891, and edges 0
$ python3.7 test.py
Observed 10000 of coin tossing with heads 4968, tails 5032, and edges 0
$ python3.7 test.py
Observed 10000 of coin tossing with heads 5046, tails 4954, and edges 0
Upvotes: 0