python - 谁能告诉我为什么我的代码显示错误的 pi 值?

标签 python pi

This is the equation i'm trying to use in the while loop这是我的输出图片:

enter image description here

inptTol = float(input("Enter the tolerance: "))
print()

term = 1
divNum = 3
npower = 1
sumPi = 0.0
count = 0

while abs(term) > inptTol:
    sumPi += term
    term = -term/(divNum * (3**npower))
    divNum += 2
    npower += 1
    count += 1

sumPi = math.sqrt(12) * sumPi  
pythonPi = math.pi  
approxError = abs (sumPi - pythonPi)  

print("The approximate value of pi is %.14e\n" \
        "       Python's value of pi is %.14e\n"
        "The error in the approximation of pi is %.6e\n"
        "The number of terms used to calculate the value of pi is %g " %
        (sumPi, pythonPi, approxError, count))  

这些是它显示的值:

pi的近似值为3.08770957930231e+00

Python的pi值为3.14159265358979e+00

我想让它给我看这个:

pi的近似值为3.14159265358979

Python 的 pi 值为 3.14159265358979

最佳答案

我认为您缺少信号。显然你试图这样做,但改变了上一个术语信号并在下一个术语中使用它。 看我的代码,我试着像他那样做。你怎么看?

import math
inptTol = float(input("The tolerance: "))

signal = 1.0
term = 1.0
divNum = 3.0
npower = 1.0
sumPi = 0.0
count = 0.0

while inptTol < abs(term):
    signal *= -1.0
    sumPi += term
    term = signal / (divNum * (3.0 ** npower))
    divNum += 2.0
    npower += 1.0
    count += 1.0

sumPi *= math.sqrt(12.0)
pythonPi = math.pi  
approxError = abs(sumPi - pythonPi)  

print("The approximate value of pi is %.14f\n" \
        "       Python's value of pi is %.14f\n"
        "The error in the approximation of pi is %.6e\n"
        "The number of terms used to calculate the value of pi is %g " %
        (sumPi, pythonPi, approxError, count))

关于python - 谁能告诉我为什么我的代码显示错误的 pi 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35049772/

相关文章:

node.js - 找不到 module express,如何安装它以使其在全局范围内可用?

python - CRC32计算

c - 这段代码如何高精度地计算圆周率?

c++ - 为什么 C++11 标准中没有常量 pi 的定义?

python - 迭代 groupby 数据帧以在每一行中进行操作

java - 在 Android 手机上计算圆周率

python - pyschools 主题 5

python - rec2csv 导出时行之间有空行

python - 使用 psycopg2 创建 postgresql 数据库

python - 在 python 中绘制二进制数据