continuedfractions#
A simple extension of the Python fractions
standard library for working with continued fractions as Python objects.
The package is designed for:
working with continued fractions as Python objects
exploring their key continued fractions properties, such as elements/coefficients, convergents, remainders, and other numerical properties etc.
operating on them fully as rational numbers and instances of the standard library
fractions.Fraction
classsupporting approximations of and experimental computations for irrational numbers
exploring other related objects, such as mediants, and special sequences of rational numbers such as Farey sequences
Note
Currently, it does not support the following features:
infinite and generalised continued fractions
symbolic computations
These are planned for future releases.
You can start here, or go straight to the API reference.
Prelude#
>>> import decimal, math; from continuedfractions.continuedfraction import ContinuedFraction
>>> cf = ContinuedFraction(math.pi)
>>> cf
ContinuedFraction(884279719003555, 281474976710656)
>>> cf.elements
(3,7,15,1,292,1,1,1,2,1,3,1,14,4,2,3,1,12,5,1,5,20,1,11,1,1,1,2)
>>> cf.as_decimal()
Decimal('3.141592653589793115997963468544185161590576171875')
>>> cf.convergent(0), cf.convergent(1), cf.convergent(2), cf.convergent(10), cf.convergent(20), cf.convergent(27)
(ContinuedFraction(3, 1), ContinuedFraction(22, 7), ContinuedFraction(333, 106), ContinuedFraction(4272943, 1360120), ContinuedFraction(509453239292, 162164002615), ContinuedFraction(884279719003555, 281474976710656))
>>> cf.order
27
>>> pi_approx = ContinuedFraction.from_elements(3, 7, 15, 1, 292)
>>> pi_approx
ContinuedFraction(355, 113)
>>> pi_approx.as_float()
3.1415929203539825
>>> math.pi - pi_approx.as_float()
-2.667641894049666e-07
>>> import pytest
>>> pytest.approx(pi_approx.as_float(), abs=1e-6) == math.pi
True