蒙特卡罗法近似求解圆周率π
发布日期:2021-07-01 03:25:02 浏览次数:2 分类:技术文章

本文共 1136 字,大约阅读时间需要 3 分钟。

文章目录

1. 原理

在这里插入图片描述

  • 给出 x ∈ [ 0 , 1 ) , y ∈ [ 0 , 1 ) x \in [0,1),y\in[0,1) x[0,1),y[0,1) 的均匀分布随机点,模拟 t t t 次,落在以 ( 0 , 0 ) (0,0) (0,0) 为圆心,半径 r = 1 r=1 r=1 的圆以内的次数为 c c c
  • 当模拟次数足够大时,可以看成面积比 π 4 ≈ c t ⇒ π ≈ 4 c / t \frac{\pi}{4} \approx \frac{c}{t}\Rightarrow \pi \approx 4c/t 4π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 randomimport matplotlib.pyplot as pltsimulations = [100, 1000, 10000]plt.figure()plt.rcParams['font.sans-serif'] = 'SimHei'  # 消除中文乱码plotid = 1color = ['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()

在这里插入图片描述

转载地址:https://michael.blog.csdn.net/article/details/105886943 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode 1318. 或运算的最小翻转次数(位运算)
下一篇:潜在狄利克雷分配(Latent Dirichlet Allocation,LDA)

发表评论

最新留言

很好
[***.229.124.182]2024年04月12日 15时16分03秒