# -*- coding: utf-8 -*- import math import random def nCr(n,r): f = math.factorial out = f(n) / (f(r)*f(n-r)) return out random.seed(10) p_heads = 0.5 n_trials = 10 k_heads = 2 res = nCr(n_trials,k_heads)*(p_heads**k_heads)*((1.0-p_heads)**(n_trials-k_heads)) print res step_max = 100000 success = 0.0 for i in range(1,step_max): sum = 0 for j in range(1,n_trials+1): coin = random.random() if coin < p_heads: sum = sum + 1 if sum == k_heads: success = success + 1.0 print success,step_max,success/step_max