在Python中,计算圆周率可以通过多种方法实现,以下是几种常见的方法:
使用内置的`math`模块
import mathpi = math.piprint(pi) 输出圆周率的近似值
使用蒙特卡洛方法
import randomdef estimate_pi(n):inside_circle = 0total_points = 0for _ in range(n):x = random.uniform(0, 1)y = random.uniform(0, 1)distance = x2 + y2if distance <= 1:inside_circle += 1total_points += 1return 4 * inside_circle / total_pointsn = 10000 采样点数pi_estimate = estimate_pi(n)print(f"估计的圆周率为: {pi_estimate:.6f}")```使用级数展开公式
```pythonimport mathdef calculate_pi(n):sum = 0for k in range(n):sum += 4 * ((-1) k) / (2 * k + 1)return sumn = 1000 级数展开的项数pi_estimate = calculate_pi(n)print(f"通过级数展开计算的圆周率为: {pi_estimate:.6f}")
使用其他数学公式
from random import randomfrom time import perf_counterDARTS = 投掷次数hits = 0.0start = perf_counter()for i in range(1, DARTS + 1):x, y = random(), random()dist = pow(x 2 + y 2, 0.5)if dist <= 1.0:hits += 1pi = 4 * (hits / DARTS)print(f"通过蒙特卡洛方法计算的圆周率为: {pi:.6f}")
以上代码展示了使用不同方法计算圆周率的基本示例。你可以根据具体需求选择合适的方法,并调整参数以获得更精确的结果。需要注意的是,随着采样点数或级数展开项数的增加,计算圆周率的结果会趋于精确,但计算时间也会相应增加

