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))
表示されている値は次のとおりです。
円周率の概算値は3.08770957930231e + 00です。
Pythonの円周率の値は3.14159265358979e + 00です
私はそれが私にこれを見せたいです:
円周率の概算値は3.14159265358979です。
Pythonの円周率の値は3.14159265358979です
私の場合、問題はあなたがterm
価値を変えるからです。それがなければならない1
か、-1
署名します- 。
私のバージョン-私はfor
ループを使用します
import math
terms_number = float(input("Enter terms number: "))
sign = 1
divNum = 1
npower = 0
sumPi = 0.0
count = 0
for x in range(terms_number):
sumPi += sign/(divNum * (3**npower))
# values for next term
sign = -sign
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))
7期の結果
The approximate value of pi is 3.14167431269884e+00
Python's value of pi is 3.14159265358979e+00
The error in the approximation of pi is 8.165911e-05
The number of terms used to calculate the value of pi is 7
15期の結果
The approximate value of pi is 3.14159265952171e+00
Python's value of pi is 3.14159265358979e+00
The error in the approximation of pi is 5.931921e-09
The number of terms used to calculate the value of pi is 15
編集:あなたのwhile
ループのあるバージョン
import math
inptTol = float(input("Enter the tolerance: "))
term = 1
sign = 1
divNum = 1
npower = 0
sumPi = 0.0
count = 0
while abs(term) > inptTol:
term = sign/(divNum * (3**npower))
sumPi += term
# values for next term
sign = -sign
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))
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加