掷骰子在 'k' 次中恰好获得两个 3 的概率

Rolling of Dice probability of getting exactly two 3s in 'k' rolls

尝试计算在 'k' 掷骰中获得两个 3 的概率,然后计算条形图。在我添加以 prob_trials[] 开头的代码之前,它不会 return 任何输出。然后当我添加 prob_trials[] 代码时,如果得到 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)

这是因为您在元组名称后放置了普通括号 (),而您应该使用方括号 [].

事实上,您可能想要做的只是遍历元组,这样您就不必首先为它建立索引:

prob_trials=[]
for i in trial_result:
    a = i / 100
    prob_trials.append(a)

此外,pltbar 未定义,因此会给您一个错误。我不熟悉 pylab 模块,但我可以大胆猜测您的实际意思是:

pylab.pltbar(dice,prob_trials)

(虽然我可能是错的)

我建议直接计算概率。掷骰子实验得到

  1. '3' 概率为 1/6
  2. 'not 3' 概率为 5/6

这可以看作是 Bernoulli distribution. Thus, the act of 2 successes in k experiments will be regarded as Binomial distribution。因此,二项式随机变量 Xk 次尝试中获得 2 次成功的概率将计算为:

P(X=2) = (k choose 2)*(1/6)^2 * (5/6)^{k-2}

此代码示例为:

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)