Skip to main content
 首页 » 编程设计

Python 无限系列 pi/4

2024年10月24日13langtianya

我有一个问题要解决,但我遇到了一些麻烦。这是问题所在:

π/4的值可以近似为无限级数:1−1/3+1/5−1/7...

让您的程序提示用户使用多少项进行近似,然后显示结果。还通过从 Python 的 math.pi 值中减去近似答案向用户显示引入了多少错误。

示例:用户输入 4。近似值为 ~.723809524。错误 = ~0.06158863939745

这是我的代码:

def proj3_6(): 
    print("This is a program that will approximate the value of pi / 4") 
    numberOfTerms = eval(input("How many terms should be used for the    approximation? ")) 
    expr = math.pi / 4 
    roundedExpr = round(expr, numberOfTerms) 
    error = math.pi - roundedExpr 
    print("The approximation is: ", roundedExpr) 
    print("The error would be: ", error) 

出于某种原因,它打印出错误的近似值和误差。我做错了什么?

请您参考如下方法:

您需要在代码中使用某种循环来遍历系列的每一部分。可以使用以下方法解决问题:

import itertools 
import math 
 
terms = int(input("How many terms should be used for the approximation? ")) 
pi4 = 0.0 
 
for numerator, denominator in zip(itertools.cycle([1.0, -1.0]), range(1, terms * 2, 2)): 
    pi4 += float(numerator) / denominator 
 
print("Approximated value is ~", pi4) 
print("Error is ~", (math.pi / 4.0) - pi4) 

给你输出:

How many terms should be used for the approximation? 4 
Approximated value is ~ 0.7238095238095239 
Error is ~ 0.061588639587924376 

range 用于给出数字 1 3 5 7,itertools.cycle 用于生成交替的 1.0 -1.0 序列。 zip 用于将两者结合起来进行循环。