编写python程序 兀 3_用python语言算π值并且带有进度条
时间: 2024-03-11 21:50:53 浏览: 84
以下是一个用 Monte Carlo 方法计算 π 值并带有进度条的 Python 程序:
```python
import random
import time
def estimate_pi(n):
num_points_inside_circle = 0
for i in range(n):
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)
if x**2 + y**2 <= 1:
num_points_inside_circle += 1
pi_estimate = 4 * num_points_inside_circle / n
return pi_estimate
def progress_bar(progress):
bar_length = 20
filled_length = int(round(bar_length * progress))
bar = '=' * filled_length + '-' * (bar_length - filled_length)
print(f'\r[{bar}] {progress*100:.1f}%', end='')
n = 1000000
start_time = time.time()
for i in range(n):
pi_estimate = estimate_pi(i+1)
progress = (i+1) / n
progress_bar(progress)
end_time = time.time()
print(f'\n\nFinal estimate of π: {pi_estimate:.5f}')
print(f'Time taken: {end_time - start_time:.2f} seconds')
```
该程序使用了 `random.uniform()` 函数生成随机坐标来模拟在 [-1, 1] x [-1, 1] 正方形内随机投掷点的过程。如果点落在单位圆内,则计数器加一。最后,π 值的估计值为 4 * 圆内点数 / 总点数。
在计算过程中,我们使用 `progress_bar()` 函数来输出进度条。该函数接受一个参数 `progress`,表示当前完成的任务比例。它会根据 `progress` 的值,在一行中输出一个进度条,显示当前任务完成的百分比。
在主程序中,我们循环调用 `estimate_pi()` 函数来逐步计算 π 值的估计值,并输出进度条。最后输出最终的 π 值估计值和程序运行时间。
阅读全文