Note
Go to the end to download the full example code.
Approximating pi by continued fractions#
Expands pi as a continued fraction and shows how quickly its convergents (355/113 famously accurate to 7 digits) approach the true value.
import numpy as np
from mathematicskit.number_theory import best_rational_approximation, continued_fraction_expansion
from mathematicskit.number_theory.visualizers.plots import plot_convergent_errors
Expand pi and inspect its convergents#
terms: [3, 7, 15, 1, 292, 1, 1, 1]
3/1 = 3.0000000000 (error 1.42e-01)
22/7 = 3.1428571429 (error 1.26e-03)
333/106 = 3.1415094340 (error 8.32e-05)
355/113 = 3.1415929204 (error 2.67e-07)
103993/33102 = 3.1415926530 (error 5.78e-10)
104348/33215 = 3.1415926539 (error 3.32e-10)
208341/66317 = 3.1415926535 (error 1.22e-10)
312689/99532 = 3.1415926536 (error 2.91e-11)
Best approximation under a denominator bound#
best approximation with denominator <= 1000: 355/113
Plot the convergent errors#
plot_convergent_errors(result, x=np.pi)

<Axes: title={'center': 'Continued-fraction convergent error'}, xlabel='denominator q', ylabel='|p/q - x|'>
Total running time of the script: (0 minutes 0.029 seconds)