-1

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)
Barmar
  • 741,623
  • 53
  • 500
  • 612
J04c0
  • 11
  • 4
  • See https://stackoverflow.com/questions/3477283/what-is-the-maximum-float-in-python the maximum float is about `1.7e308`, i.e. 308 decimal digits. – Barmar Oct 08 '21 at 16:02
  • On my pc the result does not change past `calculus(22)`. Why do you need more iterations? – Wombatz Oct 08 '21 at 16:05
  • It does change in between larger iterations. Calculating Pi it's something of exactitud, so you need to go "bigger" for more of this exactitud. – J04c0 Oct 08 '21 at 16:08
  • @J04c0 But floats aren't exact... Maybe you want to use [`decimal`](https://docs.python.org/3/library/decimal.html) instead, which supports arbitrary precision. – wjandrea Oct 08 '21 at 16:52

1 Answers1

0

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.

Milad
  • 164
  • 5