Continued fraction with relative precision in Python I have the following recursive function to compute the continued fraction:

$$s_i = \frac{a_{i}}{b_{i} + s_{i+1}}$$

The relative error is defined as:

$$\text{Delta} = \frac{s_n - s_{n-1}}{s_{n}}$$

Here is the implementation in Python, of Lentz's method for computing continued fractions:

import numpy as np

def n_continued_fraction(a, b, err, i_min=3):
    f = lambda i : a(i)
    g = lambda i : b(i)
    d = lambda i : 1./g(0) if i == 0 else 1./(g(i) + f(i) * d(i-1))
    h = lambda i : 0 if i == -1 else f(0)/g(0) if i == 0 else (h(i-1) * g(i) + h(i-2) * d(i-1) * f(i)) * d(i)
    delta_h = lambda i : h(i) - h(i-1)

    i_final = i_min

    while np.abs(delta_h(i_final)) &gt; err * np.abs(h(i_final)):
        i_final += 1

    return h(i_final)


and you can test it with e.g.

a = lambda i : (i+1.)
b = lambda i : (i+5.)

n_continued_fraction(a, b, 1.e-16)


Is there a better method to do it? Am I doing anything wrong?
Nice code, it does what it should and it is short. But it can be improved :)



General python tips:


Use type annotation. You can look at the type annotation of Sam Stafford in the previous answer, it will make your code more readable and will prevent bugs.
Remove redundant imports. Is numpy really needed here? You can use a simple abs.
Don't use lambda functions. According to PEP 8 "do not assign lambda expression, use a def", there are several reasons why, mostly due to readability.




Optimisation tips:
Note these tips contradict each other. Choose one and use it but you cannot use both.


If N is the number of elements until convergence, and a and b is the calculation time of each function (Assuming equal for every x) The time complexity now is O(N ^ 2 * a * b), for each i you calculate the entire series over and over.
If you will use exponential search you can reduce the complexity to O(N * log N * a * b). Which will be much much faster!
Readability vs. Runtime. If the readability is important to you you can ignore this tip. You can replace the recursion with a dynamic programing approach, this will remove the recursion and the iteration over i, the time complexity will be O(N * a * b) but you will need to rewrite a lot of the code.