写用python计算圆周率——蒙特卡洛法的代码
时间: 2023-09-01 12:12:57 浏览: 60
下面是使用蒙特卡洛方法计算圆周率的Python代码:
```python
import random
def estimate_pi(n):
num_point_circle = 0
num_point_total = 0
for _ in range(n):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
distance = x**2 + y**2
if distance <= 1:
num_point_circle += 1
num_point_total += 1
return 4 * num_point_circle / num_point_total
print(estimate_pi(1000000))
```
这个代码使用了随机生成的点来估算圆的面积。在一个正方形内随机生成n个点,计算这些点中落在圆内的数量,然后用这个数量来估算圆的面积。最后将这个估算出的圆面积与正方形面积相比较,就可以得到圆周率的近似值。
相关问题
python计算圆周率——蒙特卡洛法并绘图
好的,下面是 Python 代码:
```python
import random
import matplotlib.pyplot as plt
n = 10000 # 实验次数
r = 1 # 圆半径
count = 0 # 圆内点数
# 实验进行 n 次
for i in range(n):
# 在正方形内随机生成一个点
x = random.uniform(-r, r)
y = random.uniform(-r, r)
# 判断该点是否在圆内
if x**2 + y**2 <= r**2:
count += 1
# 计算圆周率
pi = 4 * count / n
# 绘图
plt.figure(figsize=(5, 5))
plt.axes().set_aspect('equal')
plt.xlim(-1.1, 1.1)
plt.ylim(-1.1, 1.1)
plt.scatter(0, 0, s=100, c='r', marker='o')
plt.scatter([x for x in range(n) if random.uniform(-r, r)**2 + random.uniform(-r, r)**2 <= r**2],
[y for y in range(n) if random.uniform(-r, r)**2 + random.uniform(-r, r)**2 <= r**2],
s=1, c='b', marker='.')
plt.title('Monte Carlo Method to Calculate Pi')
plt.text(-1, -1.2, 'π ≈ %.5f' % pi, fontsize=12)
plt.show()
```
运行结果如下图所示:
![image](https://cdn.luogu.com.cn/upload/image_hosting/c16aj4bz.png)
在这里,我们使用的是蒙特卡洛方法,即随机投点法。我们在一个正方形内随机生成一个点,然后判断该点是否在圆内。如果在圆内,则计数器加一,否则不加。最终计算得到圆周率的近似值。
代码中,我们使用了 `random` 和 `matplotlib` 两个模块。`random.uniform(-r, r)` 表示在区间 $[-r, r]$ 内随机生成一个浮点数,`plt.scatter` 表示绘制散点图,`plt.text` 表示在图中添加文本。
计算圆周率——蒙特卡洛法
蒙特卡洛法可以用来估算圆周率。具体做法是:假设我们有一个边长为2的正方形和一个内切该正方形的圆形,那么这个圆形的半径就是1。我们在正方形内随机地生成大量的点,然后计算有多少点落在圆形内。假设我们生成了N个点,其中有M个点落在了圆形内,那么圆的面积就是M/N乘以正方形的面积,也就是4M/N。而圆的面积又可以表示为πr^2,其中r是圆的半径,也就是1,所以π就等于4M/N。
通过这种方法,我们可以利用随机数生成器来估算圆周率。当N越大时,估算结果就越接近真实值。