当前位置:网站首页>用蒙特卡洛法求圆周率pi
用蒙特卡洛法求圆周率pi
2022-06-22 06:04:00 【fire2fire2】
思路
正方形的面积为:
圆的面积为:
圆的面积比上正方形的面积为:π / 4
使用蒙特卡洛法在正方形内随机撒点,落在圆内的点 / 落在正方形内的点(全部的点),就约等于圆的面积 / 正方形的面积 = π / 4
代码实现以第一象限的1/4圆为例。
代码
import random
def count_pi(n):
#这里用1/4圆写代码逻辑
i = 0
count = 0
# n 为传入的总点数量
while i < n:
# 随机产生x,y坐标
# random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0
x = random.random()
y = random.random()
# 如果x平方 + y平方 < 1,说明在圆内
if (pow(x, 2) + pow(y, 2)) < 1:
count += 1
i += 1
# π的值为:4 * (落在圆内的点/总的点)
return 4 * (count / n)
pi = count_pi(100000)
print(pi)
运行结果
运行100次,取平均值。
蒙特·卡罗方法(Monte Carlo method),也称统计模拟方法,一种以概率统计理论为指导的一类非常重要的数值计算方法。是指使用随机数(或更常见的伪随机数)来解决很多计算问题的方法。
边栏推荐
- DataBricks从开源到商业化踩过的坑
- 常用CMOS模拟开关功能和原理
- Expert PID control in Simulink
- Server PHP related web page development environment construction
- pip升级难题(已解决)You are using pip version 19.0.3, however version 22.1.2 is available.
- Design input of Oracle project management system
- Single cell paper records (Part8) -- cell2location maps fine grained cell types in spatial transcriptomics
- BinaryFormatter saving and loading game data for unity
- Machine learning concept sorting (no formula)
- Single cell literature learning (Part2) -- stplus: a reference based method for the exact enhancement of St
猜你喜欢

Single cell paper record (Part11) -- clustermap for multi-scale clustering analysis of spatial gene expression

Research on automatic landing control system of carrier aircraft

System identification of automatic control principle

MFC tab control add Icon

C#中的泛型

单细胞论文记录(part14)--CoSTA: unsupervised convolutional neural network learning for ST analysis

富设备平台突破:基于RK3568的DAYU200进入OpenHarmony 3.1 Release主干

单细胞论文记录(part8)--Cell2location maps fine-grained cell types in spatial transcriptomics

matlab 的离散pid控制

Linear regression: least squares, Tellson estimation, RANSAC
随机推荐
Linear regression: least squares, Tellson estimation, RANSAC
生信文献学习(part1)--PRECISE: a ... approach to transfer predictors of drug response from pre-clinical ...
Simple use of idea plug-in easy code
关于jinja2 宏定义的小问题
Signal output library
EPP (enhanced parallel port)
单细胞文献学习(part2)--stPlus: a reference-based method for the accurate enhancement of ST
402-字符串(题目:剑指Offer58-II.左旋转字符串、 28. 实现 strStr()、459.重复的子字符串)
Single cell literature learning (Part2) -- stplus: a reference based method for the exact enhancement of St
PyG教程(7):剖析邻域聚合
MFC TabCtrl 控件修改标签尺寸
401-字符串(344. 反转字符串、541. 反转字符串II、题目:剑指Offer 05.替换空格、151. 颠倒字符串中的单词)
Generics in C #
单细胞论文记录(part8)--Cell2location maps fine-grained cell types in spatial transcriptomics
MFC tabctrl control to modify label size
Single precision, double precision and precision (Reprint)
Unity app improves device availability
【自己动手写CPU】异常相关指令的实现
富设备平台突破:基于RK3568的DAYU200进入OpenHarmony 3.1 Release主干
Performance optimization best practices for reducing Game Size