i'm working on basic calculus and factorials with python. Trying to produce PI from newton series, but i cant go further than 171 iterations because of this error: OverflowError: int too large to convert to float. Here's the code:
i've imported this: 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)
CodePudding user response:
According to Python Tutorial in cases where precision is important it's better to use decimal
or fractions
modules.
For example, instead of writing f2 = 1/(exp 1)
you should write
from fractions import Fraction
f2 = Fraction(1, exp 1)
Read this article to get a better understanding.
Note that doing such heavy computations is not recommended in Python itself even with built-in libraries like fractions
. You should use libraries such as NumPy for better performance and also better precision.