蒙特卡罗法近似求解圆周率π
生活随笔
收集整理的這篇文章主要介紹了
蒙特卡罗法近似求解圆周率π
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 1. 原理
- 2. 模擬代碼
1. 原理
- 給出 x∈[0,1),y∈[0,1)x \in [0,1),y\in[0,1)x∈[0,1),y∈[0,1) 的均勻分布隨機(jī)點(diǎn),模擬 ttt 次,落在以 (0,0)(0,0)(0,0) 為圓心,半徑 r=1r=1r=1 的圓以內(nèi)的次數(shù)為 ccc
- 當(dāng)模擬次數(shù)足夠大時(shí),可以看成面積比 π4≈ct?π≈4c/t\frac{\pi}{4} \approx \frac{c}{t}\Rightarrow \pi \approx 4c/t4π?≈tc??π≈4c/t
2. 模擬代碼
# -*- coding:utf-8 -*- # @Python Version: 3.7 # @Time: 2020/5/2 9:02 # @Author: Michael Ming # @Website: https://michael.blog.csdn.net/ # @File: monte_carlo_cal_pi.py # @Reference: import random import matplotlib.pyplot as pltsimulations = [100, 1000, 10000] plt.figure() plt.rcParams['font.sans-serif'] = 'SimHei' # 消除中文亂碼 plotid = 1 color = ['r', 'b'] for i in range(len(simulations)):f = plt.subplot(1, 3, plotid)plotid += 1count = 0t = simulations[i]time = simulations[i]while time > 0:time -= 1x = random.random() # [0,1)y = random.random() # [0,1)val = x ** 2 + y ** 2pos = 1if (val < 1):pos = 0count += 1f.scatter(x, y, c=color[pos])pi = 4 * count / tf.set_title("模擬次數(shù){},pi的值{:.4f}".format(t, pi)) plt.suptitle("蒙特卡羅法近似求解圓周率pi") plt.show() 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的蒙特卡罗法近似求解圆周率π的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: LeetCode 456. 132模式(
- 下一篇: Feature Engineering