蒙特卡罗法近似求解圆周率π

文章目录

1. 原理

在这里插入图片描述

  • 给出 x [ 0 , 1 ) , y [ 0 , 1 ) x \in [0,1),y\in[0,1) 的均匀分布随机点,模拟 t t 次,落在以 ( 0 , 0 ) (0,0) 为圆心,半径 r = 1 r=1 的圆以内的次数为 c c
  • 当模拟次数足够大时,可以看成面积比 π 4 c t π 4 c / t \frac{\pi}{4} \approx \frac{c}{t}\Rightarrow \pi \approx 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 plt

simulations = [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 += 1
    count = 0
    t = simulations[i]
    time = simulations[i]
    while time > 0:
        time -= 1
        x = random.random()  # [0,1)
        y = random.random()  # [0,1)
        val = x ** 2 + y ** 2
        pos = 1
        if (val < 1):
            pos = 0
            count += 1
        f.scatter(x, y, c=color[pos])
    pi = 4 * count / t
    f.set_title("模拟次数{},pi的值{:.4f}".format(t, pi))
plt.suptitle("蒙特卡罗法近似求解圆周率pi")
plt.show()

在这里插入图片描述

原创文章 1015 获赞 3760 访问量 55万+

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/105886943