計算 pi 的數值
現在要實作一個經典範例——估計 \(\pi\) 的數值。
想像一個邊長為 2 的正方形,以原點 \((0, 0)\) 為中心,四個頂點座標為 $(1, 1), (1, -1), (-1, 1), (-1, -1)$。這個正方形的面積是 $2\times 2 = 4\(。再想像一個半徑為 1、圓心在原點的圓,剛好內切在這個正方形裡。這個圓的面積是 \)\pi \times \text{radius}^2 = \pi$。
為了估計 $\pi$,我們在這個正方形內隨機抽樣許多點,並計算落在圓內的點所佔比例(滿足 $x^2 + y^2 <= 1\()。圓的面積等於這個比例的 4 倍,這就給出我們對 \)\pi$ 的估計。
完成這個練習後,你會更熟悉如何用模擬來進行計算。
本練習屬於課程
Python 的統計模擬
練習說明
- 在主控台用
np.pi查看 \(\pi\) 的真值。將sims設為 10000,circle_points設為 0。 - 在
for迴圈內,使用np.random.uniform()在 -1 到 1 之間產生一個點(x 與 y 座標),並指定size=2。 - 用方程式 \(x^2 + y^2 <= 1\) 檢查該點是否位於單位圓內,指定給
within_circle,並依此遞增circle_points。 - 將圓內點所佔比例乘以 4,印出 \(\pi\) 的估計值
pi_sim。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Initialize sims and circle_points
sims, circle_points = ____, ____
for i in range(sims):
# Generate the two coordinates of a point
point = ____
# if the point lies within the unit circle, increment counter
within_circle = point[0]**2 + point[1]**2 <= 1
if ____ == True:
circle_points +=1
# Estimate pi as 4 times the avg number of points in the circle.
pi_sim = ____
print("Simulated value of pi = {}".format(pi_sim))