我正在使用 python 研究基本的微積分和階乘。試圖從牛頓系列生成 PI,但由于這個錯誤,我不能超過 171 次迭代:溢位錯誤:int 太大而無法轉換為浮點數。這是代碼:
我已經匯入了這個: from math import factorial, gamma / from math import sqrt
def calculus(ran):
x = 1/2
exp = 0
p = 0
terminos = []
length = len(terminos)
for i in range(ran):
k = i
n = 1/2
tzero = 1
exp = 2
num = gamma(n)
if k != 0:
den1 = factorial(k)
den2 = n-k
den3 = gamma(den2)
den = den1 * den3
f1 = num/den
f2 = 1/(exp 1)
f3 = x**(exp 1)
terminos.append(f1*f2*f3)
else:
f1 = x
f2 = 1
f3 = 1
terminos.append(f1*f2*f3)
p = 0
terminos.append(-sqrt(3)/8)
serie = sum(terminos)
pi = serie * 12
print(pi)
calculus(172)
uj5u.com熱心網友回復:
根據Python 教程,在精度很重要的情況下,最好使用decimal或fractions模塊。
例如,f2 = 1/(exp 1)你應該寫而不是寫
from fractions import Fraction
f2 = Fraction(1, exp 1)
閱讀這篇文章以獲得更好的理解。
請注意,即使使用像fractions. 您應該使用諸如NumPy 之類的庫以獲得更好的性能和更高的精度。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/312871.html
