python概率计算事件下一次发生概率_Python For Loop和If语句在掷硬币概率计算中的应用...

我觉得你的代码还存在一些缺陷,比如你需要用浮点除法代替整数除法(适当的类型转换),你的条件概率计算公式需要修正,你计算的概率实际上是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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值