Continued fraction for pi in Python

Question:

I’m trying to approximate pi using continued fraction.

I’m using this formula.

enter image description here

After many hours, I ended up here.

for i in range(1,15,1):
    e = ((2*i - 1) ** 2)
    b = (e / (6 + ((2*(i+1) - 1) ** 2)))

    print(3+b)

`

But my output is not so great…

enter image description here

Asked By: user18701301

||

Answers:

Your approach is incorrect. If you substitute some example values in place of i you will notice that you completely disregard everything other than i-th and i+1th part of this fraction. You need to make sure that your loop takes into account all the higher levels as well as the new one you are calculating. I think the easiest way to code the solution is by using recursion:

def inf_pi(its, ctr = 1):
    if its == 0:
        return 0
    else:
        x = ((2*ctr)-1)**2 / (6 + inf_pi(its - 1, ctr + 1))
        return  x + (3 if ctr == 1 else 0)

print(inf_pi(10))

If you need an iterative approach, you have to consider 2 things – first of all, you can only calculate this with finite precision, and you need to replace the uncalculated remainder with some value. Second problem is that you are trying to calculate this from outermost fraction, but you don’t know what the value of the "infinite" fraction is. If you reverse the order, starting form the innermost fraction, after replacing part outside of wanted precision with a constant, you can keep calculating a value for each step all the way up to the outer fraction.

def it_pi(its):
    pi = 0
    for i in range(its, 0, -1):
        pi = (((2*i)-1)**2) / (6 + pi)
    return 3 + pi
Answered By: matszwecja

You can define a sequence in the following manner:

enter image description here

I chose to do with 500 terms, you could do more, but mind to change the recursion depth.

def cont_frac(n=1, m=500):
    if n==m:
        return 1
    return 6+(2*n+1)**2/cont_frac(n+1)
    
pi = 3+1/cont_frac()
print(pi)

Here’s my output:

3.1415926515817754

Answered By: Nothing special
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.