#蒙地卡羅模擬法,是基於大數法則的實證方法,當實驗的次數越多,其平均值也就會越趨近於理論值。
import matplotlib.pyplot as plt
import numpy as np
import random
plt.figure(figsize=(8,8),dpi=80)
t = np.linspace(0,0.5*np.pi,100)
x=np.cos(t)
y=np.sin(t)
plt.plot(x,y,color="green",linewidth=5)
N=2000
count=0 #計數
for i in range(1,N+1):
x=random.random() #輸出0-1之間的隨機數
y=random.random()
# print ("(",x,",",y,")")
if (x*x+y*y<=1):
count=count+1
plt.scatter(x,y,color="red",linewidth=1)
else:
plt.scatter(x,y,color="white",linewidth=1)
print("估計值=",count/N)
print("理論值=",np.pi/4)
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.show()