Python无穷级数pi/4

2024-09-27 21:23:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

π/4的值可以用无穷级数近似:1−1/3+1/5−1/7。。。在

让你的程序提示用户使用多少术语来近似,然后显示结果。还可以通过从Python中减去近似答案,向用户显示引入了多少错误数学.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)

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


Tags: the用户is错误pierrormathbe
1条回答
网友
1楼 · 发布于 2024-09-27 21:23:10

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

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)

给出输出:

^{pr2}$

range用于给出数字1 3 5 7,而{}用于产生一个交替的1.0 -1.0序列。zip用于为循环组合这两者。在

相关问题 更多 >

    热门问题