π近似 - 莱布尼兹系列

时间:2017-03-15 11:29:51

标签: python

我对John Zelle Python编程:计算机科学概论(第2版)一书中为练习编写的代码的有效性表示担忧。

它说:

  

通过对术语求和来编写一个近似于π值的程序   本系列:4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ......该计划   应该提示用户输入n,术语总数,然后   输出本系列前n个项的总和。有你的程序   从math.pi的值中减去近似值,看看如何   准确无误。

这就是我所做的:

# pi_approximation
#   Program which approximates the value of Pi by summing the terms of
#   this series: 4/1 - 4/3 + 4/5 - 4/7

import math

def main():

    print("Welcome to Pi approximation!\n")

    n = int(input("Enter the number of terms to sum: "))

    approx = 0

    for i in range(1, n+1, 2):
        approx += 4 / i - 4 / (i+2)

    print("Approximate value of pi is: " + str(approx))

    print("Deviation from Pi is: " + str(math.pi - approx))

main()

我正在使用Python 3.6。

3 个答案:

答案 0 :(得分:0)

for i in range(1, n+1, 2):应为for i in range(1, n+1, 4):,因为您将i部分与i + 2部分相加

答案 1 :(得分:0)

以下是完整的解决方案:

# pi_approximation
#   Program which approximates the value of Pi by summing the terms of
#   the Gregory-Leibniz series: 4/1 - 4/3 + 4/5 - 4/7

from math import pi as PI

def main():
    print("Welcome to Pi approximation!\n")
    n = int(input("Enter the number of terms to sum: "))
    approx = 0
    sign = -1

    # -- start Gregory-Leibniz series

    for i in range(1, n+1):  # do this 'n' times
        sign *= -1
        approx += sign * ( 4 / (2*i - 1) )

    # -- end Gregory-Leibniz series

    print("Approximate value of pi is:", approx)

    difference = PI - approx
    print("Deviation from Pi is:", difference)

main()  

答案 2 :(得分:0)

这是以前的答案(帮助我,谢谢)与强大的Python功能,列表理解和迭代器功能的组合,将整个算法压缩成一行。另外在我看来,对于n个术语,范围应该在2 * n + 1之前停止,因为我们只使用奇数。

approx = sum([4/i - 4/(i+2) for i in range(1, 2*n+1, 4)])

结合完整来源的测试结果证明它与大量术语汇合:

  

$ python3 leibniz.py
  欢迎来到Pi近似!

     

输入要求的项数:2000
  pi的近似值为:3.1410926536210386
  与Pi的偏差为:0.0004999999687544943