# Continued fractions via matrices

```import numpy as np coeffs = list(range(1,101,2)) # 1-99 coeffs_len = len(coeffs) continued_fraction_coefficients = np.array(coeffs, dtype=float) continued_fraction_coefficients_copy = continued_fraction_coefficients.copy() # Continued fractions via formula c0 + (1/(c1 + 1/(c2 + ...))) for i in range(len(continued_fraction_coefficients)): if i > 0: offset_from_right = coeffs_len - i prev_el = continued_fraction_coefficients[offset_from_right - 1] current_el = continued_fraction_coefficients[offset_from_right] piecewise_sum = prev_el + 1/float(current_el) # Replace the last two elems by the new piecewise sum (to use as current_el in next iteration) continued_fraction_coefficients = continued_fraction_coefficients[:-1] continued_fraction_coefficients[-1] = piecewise_sum total_sum = piecewise_sum # Continued fractions via matrix total_product = 1 for coeff in continued_fraction_coefficients_copy: coeff_mat = np.array([[coeff, 1], [1, 0]]) total_product = np.dot(total_product, coeff_mat) ratio = total_product[0,0] / total_product[1,0] print(total_sum, ratio, total_sum == ratio, np.allclose(total_sum, ratio)) """ 1.3130352855 1.3130352855 False True Note: Direct float comparison fails, but then you see that the two numbers are still considered approximately equal. Based on the idea from "An introduction to continued fractions" by A. J. van Poorten. """```