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/