import random
import numpy as np
import matplotlib.pyplot as plt
# 0->Heads
# 1->Tails
def coin_flip():
"""出现的数值是0或者1"""
return random.randint(0, 1)
# 投币的功能
# 一个记录使用的函数
list1 = []
# list是内置的函数
def monte_carlo(n):
result = 0
for i in range(n):
flip_result = coin_flip()
result = result + flip_result
prob_value = result / (i+1)
list1.append(prob_value)
plt.axhline(y=0.5, color='r', linestyle='-')
plt.xlabel('Iterations')
plt.ylabel('Probability')
plt.plot(list1)
return result/n
answer = monte_carlo(10)
print("最终的结果:", answer)
10次的结果
100次
500次
1000次
5000次的结果和1000次的结果差不多,这个需要更加庞大的算力