Created
June 26, 2020 12:23
-
-
Save ivan-pi/17d558e44dcf0bbb68cb79ab216c423a to your computer and use it in GitHub Desktop.
Basic functions for working with continued fractions. These are handy for approximating irrational numbers as ratios of integer. A Fortran solution is available at https://fortran-lang.discourse.group/t/implmentation-of-contnued-fraction/124/2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
from fractions import Fraction | |
def continued_fraction(r,steps=10): | |
cf = [] | |
for step in range(steps): | |
i = math.floor(r) | |
cf.append(i) | |
f = r - i | |
if f == 0: | |
break | |
r = 1./f | |
return cf | |
def contfrac_to_frac(seq): | |
''' Convert the simple continued fraction in `seq` | |
into a fraction, num / den | |
''' | |
num, den = 1, 0 | |
for u in reversed(seq): | |
num, den = den + num*u, num | |
return num, den | |
def main(): | |
r = (math.sqrt(3) + 1)/2 | |
print(r) | |
for i in range(2,30): | |
coeffs = continued_fraction(r,i) | |
f = Fraction(*contfrac_to_frac(coeffs)) | |
print(f,float(f),float(f)-r) | |
print(coeffs) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment