使用蒙特·卡罗方法计算圆周率近似值Python代码
时间: 2024-03-14 17:45:06 浏览: 114
下面是一个简单的 Python 代码示例,使用蒙特卡罗方法计算圆周率的近似值:
```python
import random
def estimate_pi(n):
num_points_inside_circle = 0
num_points_total = n
for _ in range(n):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
distance = (x ** 2 + y ** 2) ** 0.5
if distance <= 1:
num_points_inside_circle += 1
return 4 * num_points_inside_circle / num_points_total
print(estimate_pi(100000))
```
此代码将生成100,000个随机点,并计算这些点中有多少在半径为1的圆内。最终,它将返回 4 * 圆内点的数量 / 总点数,这将是圆周率的近似值。
相关问题
使用蒙特卡罗方法计算圆周率近似于Python
Python可以使用蒙特卡罗方法计算圆周率。蒙特卡罗方法是一种随机模拟方法,通过随机生成点的方式来估算圆的面积和正方形的面积,从而计算出圆周率。具体实现方法可以参考以下代码:
```python
import random
# 设置随机数种子
random.seed(2021)
# 模拟次数
n = 1000000
# 计数器
count = 0
# 进行模拟
for i in range(n):
# 随机生成点的坐标
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)
# 判断点是否在圆内
if x**2 + y**2 <= 1:
count += 1
# 计算圆周率
pi = 4 * count / n
print("模拟次数:", n)
print("圆周率估计值:", pi)
```
运行以上代码,可以得到圆周率的估计值。模拟次数越多,估计值越接近真实值。
使用蒙特卡罗方法计算圆周率近似值代码
蒙特卡洛方法是一种基于随机抽样的数值积分方法,通过模拟大量点落在单位正方形和其内切圆内的概率来估算圆周率π。下面是一个简单的Python代码示例:
```python
import random
def monte_carlo_pi(n_samples):
inside_circle = 0
for _ in range(n_samples):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
if x**2 + y**2 < 1:
inside_circle += 1
piapproximation = 4 * inside_circle / n_samples
return piapproximation
# 例如,我们想要计算100万次样本的圆周率估计
n_samples = 1_000_000
pi_estimate = monte_carlo_pi(n_samples)
print(f"Monte Carlo estimate of π with {n_samples} samples: {pi_estimate}")
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)