I am trying to make a program in Python that will calculate the value of the formula. The first 3 numbers of the continued fraction are this:
1 + (1**2/3), 1 + (1**2/(3+(2**2/5)), 1 + (1**2/(3+(2**2/5+(3**2/7))
To be clear I mean this:
How can I write a formula in python that will calculate the sum when my input is 5? As you see in the first picture the sum is once devided and in the second picture its devided two times in total. So the input for the first picture is 1 and for the second 2. I have called the numbers 1, 3, 5, 7, etc. b in my code and the numbers that are squared a. I don’t know how I must go further, because I need to add an extra division each time.
result = 0 n = 1 lstA = [] lstB = [] for b in range(10): if b%2 != 0: lstB.append(b) print(lstB) for a in range(1,5): lstA.append(a) print(lstA) result = lstB[0] + (lstA[0]**2/lstB[0+n]) print(result)
Does anyone know how I can make a program to calculate the value of this continued fraction with a input of 5 (division of 5 times)? I know this is a complicated question, so if you have questions, please ask me. If you think it not clear or this question is not suitable for here, please let me know. Thanks in advance!
Advertisement
Answer
I believe this is what you want. continued_fraction
will keep calling itself until it’s on the level that matches t
. Then it will work backwards through all of the divisions that were encountered, to the first call, returning the ultimate result.
def continued_fraction(t:int, i:int=1, n:int=1) -> float: return t if i >= t else i + n**2/continued_fraction(t, i+2, n+1) print(continued_fraction(5))