Trying to calculate the probability of getting two 3s in 'k' rolls and then bar plot. Prior to me adding the code starting with prob_trials[], it would not return any output. Then when I added the prob_trials[] code, if get the error of tuple not callable.
import random
import pylab
"Calculating probability of getting exactly a 3 in k rolls"
dice=(1,2,3,4,5,6)
one=0
two=0
three=0
four=0
five=0
six=0
for i in range(100):
result = random.choice(dice)
if result == 1:
one =1
elif result == 2:
two =1
elif result == 3:
three =1
elif result == 4:
four =1
elif result == 5:
five =1
elif result == 6:
six =1
trial_result = (one, two, three, four, five, six)
prob_trials=[]
for i in range(6):
a = trial_result(i)/100
prob_trials.append(a)
pltbar(dice,prob_trials)
CodePudding user response:
This is because you have put normal brackets ()
after the name of the tuple, whereas you should use square brackets []
.
In fact, what you probably want to do is simply iterate over the tuple, so that you don't have to index it in the first place:
prob_trials=[]
for i in trial_result:
a = i / 100
prob_trials.append(a)
Also, pltbar
is not defined so will give you an error. I am not familiar with the pylab
module, but I can hazard a guess that what you actually meant was:
pylab.pltbar(dice,prob_trials)
(Although I might be wrong)
CodePudding user response:
I would suggest a direct calculation of the probability. The experiment of rolling a dice getting
- '3' with probability
1/6
- 'not 3' with probability
5/6
This can be looked as a Bernoulli distribution. Thus, the act of 2
successes in k
experiments will be regarded as Binomial distribution. Therefore, the probability of a binomial random variable X
to have 2
successes in k
attempts will be computed as:
P(X=2) = (k choose 2)*(1/6)^2 * (5/6)^{k-2}
Code example for this will be:
from math import comb
p = 1/6 # probability of success in an experiment
k = 8 # number of experiments, put any number here
s = 2 # number of successes, 2 in our case
prob = comb(k, s) * p**s * (1-p)**(k-s)
print(prob)