温馨提示×

python求圆周率的代码怎么写

小亿
100
2023-10-26 02:50:07
栏目: 编程语言

Python中可以使用蒙特卡洛方法来估计圆周率。具体代码如下:

import random

def estimate_pi(n):
    inside_circle = 0
    total_points = 0

    for _ in range(n):
        x = random.uniform(0, 1)
        y = random.uniform(0, 1)
        distance = x**2 + y**2

        if distance <= 1:
            inside_circle += 1

        total_points += 1

    pi = 4 * inside_circle / total_points
    return pi

n = 10000  # 采样点数,可根据需要调整
pi_estimate = estimate_pi(n)
print(f"估计的圆周率为:{pi_estimate:.6f}")

上述代码中,我们使用了蒙特卡洛方法进行圆周率的估计。通过随机生成坐标点,并判断点是否在单位圆内,进而计算出圆周率的估计值。需要注意的是,蒙特卡洛方法的结果是一个估计值,其准确性与采样点数n有关,采样点数越大,估计值越接近真实值。

0