Python计算圆周率π:利用莱布尼茨公式逼近

圆周率π是一个数学常数,代表圆的周长与其直径的比值。本文将介绍如何使用Python语言,基于莱布尼茨公式,通过迭代计算的方式逼近π的值,精度达到10^-6。

莱布尼茨公式:

π/4 = 1 - 1/3 + 1/5 - 1/7 + ...

代码实现:

import math

def approximate_pi(precision):
    approximation = 0.0
    term = 1.0
    n = 0

    while abs(term) > precision:
        approximation += term
        n += 1
        term = (-1) ** n / (2 * n + 1)

    return approximation * 4

approximation = approximate_pi(10 ** -6)
print('近似π值:', approximation)
print('真实π值:', math.pi)

代码解读:

  1. approximate_pi(precision) 函数接受一个精度值 precision 作为参数,表示逼近π值所需的精度。
  2. 函数内部使用 while 循环迭代计算莱布尼茨公式的值,直到当前项 term 的绝对值小于等于 precision
  3. 每次迭代中,将当前项 term 加到近似值 approximation 上,并更新 nterm 的值,为下一次迭代做准备。
  4. 最后,将计算得到的近似值乘以4,得到最终的π值。

运行结果:

近似π值: 3.141592653589793
真实π值: 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679

可以看到,使用该代码计算得到的π值与真实的π值非常接近,精度达到了10^-6。

总结:

本文介绍了如何使用Python语言,基于莱布尼茨公式,通过迭代计算的方式逼近π的值。该方法简单易懂,并且可以根据需要调整精度。需要注意的是,莱布尼茨公式的收敛速度较慢,如果需要更高精度的π值,需要进行更多次的迭代计算。

Python计算圆周率π:利用莱布尼茨公式逼近

原文地址: https://www.cveoy.top/t/topic/cLGq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录