我觉得你的代码还存在一些缺陷,比如你需要用浮点除法代替整数除法(适当的类型转换),你的条件概率计算公式需要修正,你计算的概率实际上是z分数,假设是大数在IID变量的试验中,这里是修改后的代码,我认为它对您很有用:import random
from itertools import groupby
import statistics
import matplotlib.pyplot as plt
import numpy as np
# Function for biased coin
def flip(p): return 'H' if random.random() < p else 'T'
# Simulation
def simulate_three(X, N, Y, Z):
Outcome = [] # List of results
for i in range(X): # For loop for the X number of iterations
flips = [flip(0.6) for j in range(N)] # For loop for N number of coin flips
#print len(list(groupby(flips))), flips
if len(list(groupby(flips))) > Z: # If group condition is met
Outcome.append(len(list(groupby(flips)))) # store to list
prob = (1.0*len(filter(lambda x:x == 6, Outcome))) / len(Outcome) # conditional probability
expval = (1.0*sum(Outcome))/(len(Outcome)) # conditional expectation
zscore = (Y - expval) / statistics.stdev(Outcome) # by CLT, assuming IID variables, compute the z score
print prob
print expval
print zscore
weights = (1.0*np.ones_like(Outcome))/len(Outcome)
plt.hist(Outcome, weights=weights, facecolor='green', alpha=0.75)
plt.xlabel('#Groups')
plt.ylabel('Conditional Probability of Groups | (> 5 groups)')
plt.title('Conditional Probability Distribution')
plt.grid(True)
plt.show()
simulate_three(1000,10,6,5)
# 0.551198257081 : this is the conditional probability
# 6.64052287582 : this is the conditional expectation
# -0.773961977708 : this is the z-score