gmpy
gmpy copied to clipboard
Continued fraction expansion
Hello,
I 've done that, if you're interested in including it in the package:
from gmpy2 import mpz, mpq
from math import floor
def contfrac(x, n=10):
"""
Continued fraction expansion.
Parameters
----------
x : rational
A rational (mpq) number.
n : int
A positive integer, the desired number of terms of the continued
fraction expansion of `x`.
Returns
-------
list
A list of `mpz` integers, the `n` first terms of the continued
fraction expansion of `x` (or all the terms if there are less than `n`).
Examples
--------
>>> from gmpy2 import mpq
>>> cf = contfrac(mpq(10,7))
>>> print(cf)
[mpz(1), mpz(2), mpz(3)]
"""
floor_x = floor(x)
frac_x = x - floor_x
cf = [floor_x]
i = 1
while i < n and frac_x != 0:
x = 1 / frac_x
floor_x = floor(x)
cf.append(floor_x)
frac_x = x - floor_x
i += 1
return cf
def contfrac2mpq(cf):
"""
Evaluate a continued fraction.
Parameters
----------
cf : list
A list of `mpz` integers.
Returns
-------
ratinoal
A `mpq` rational number, obtained by evaluating the continued fraction
represented by `cf`.
Examples
--------
>>> from gmpy2 import mpq
>>> cf = contfrac(mpq(10,7))
>>> print(cf)
[mpz(1), mpz(2), mpz(3)]
>>> contfrac2mpq(cf)
10/7
"""
cf.reverse()
x = cf[1] + 1 / mpq(cf[0])
for i in range(len(cf))[2:]:
x = cf[i] + 1 / x
return x
# test
x = mpq(10, 7)
cf = contfrac(x)
print(contfrac2mpq(cf)) # x
print("***********************")
print(contfrac(mpq(10,7)))