艺小卤 发表于 2025-4-4 14:10:58

FishC 发表于 2025-4-4 14:11:47

Python计算圆周率的几种常见方法

方法1:使用math模块(直接获取高精度值)

import math
print(math.pi)# 输出:3.141592653589793


方法2:蒙特卡洛方法(概率模拟)

import random

def monte_carlo_pi(n):
    count = 0
    for _ in range(n):
      x, y = random.random(), random.random()
      if x**2 + y**2 <= 1:
            count += 1
    return 4 * count / n

print(monte_carlo_pi(1000000))# 示例输出:3.141764(精度随迭代次数增加)


方法3:莱布尼茨级数(收敛较慢)

def leibniz_pi(iterations):
    pi = 0
    sign = 1
    for i in range(1, iterations*2, 2):
      pi += sign * (4 / i)
      sign *= -1
    return pi

print(leibniz_pi(1000000))# 约需要百万次迭代达到3.14159精度


方法4:Chudnovsky算法(高精度快速收敛)

from decimal import Decimal, getcontext

def chudnovsky_pi(precision):
    getcontext().prec = precision+2
    C = 426880 * Decimal(10005).sqrt()
    M = 1
    L = 13591409
    X = 1
    K = 6
    S = L
    for i in range(1, precision//14+1):
      M = M * (K**3 - 16*K) // (i**3)
      L += 545140134
      X *= -262537412640768000
      S += Decimal(M * L) / X
    return C / S

print(chudnovsky_pi(100))# 计算100位精度



[*]蒙特卡洛法适合理解概率思想,但精度最低
[*]莱布尼茨级数简单但收敛缓慢
[*]Chudnovsky算法适合需要高精度的场景
[*]日常使用直接调用 math.pi 即可


注意:BBCode格式下无法显示代码高亮,实际使用时建议复制到Python环境中运行测试。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页: [1]
查看完整版本: 圆周率的问题