From bfed2fb7883fb7c472cd09afea1aad4e3f87d71b Mon Sep 17 00:00:00 2001 From: Saksham1970 <45041294+Saksham1970@users.noreply.github.com> Date: Wed, 16 Aug 2023 12:54:12 +0530 Subject: [PATCH] Added Continued fractions (#6846) * updating DIRECTORY.md * added continued fractions * updating DIRECTORY.md * Update maths/continued_fraction.py Co-authored-by: Caeden Perelli-Harris * Update maths/continued_fraction.py Co-authored-by: Caeden Perelli-Harris --------- Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Caeden Perelli-Harris Co-authored-by: Tianyi Zheng --- DIRECTORY.md | 1 + maths/continued_fraction.py | 51 +++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 maths/continued_fraction.py diff --git a/DIRECTORY.md b/DIRECTORY.md index be5fa3584..8d1567465 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -555,6 +555,7 @@ * [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py) * [Collatz Sequence](maths/collatz_sequence.py) * [Combinations](maths/combinations.py) + * [Continued Fraction](maths/continued_fraction.py) * [Decimal Isolate](maths/decimal_isolate.py) * [Decimal To Fraction](maths/decimal_to_fraction.py) * [Dodecahedron](maths/dodecahedron.py) diff --git a/maths/continued_fraction.py b/maths/continued_fraction.py new file mode 100644 index 000000000..25ff649db --- /dev/null +++ b/maths/continued_fraction.py @@ -0,0 +1,51 @@ +""" +Finding the continuous fraction for a rational number using python + +https://en.wikipedia.org/wiki/Continued_fraction +""" + + +from fractions import Fraction + + +def continued_fraction(num: Fraction) -> list[int]: + """ + :param num: + Fraction of the number whose continued fractions to be found. + Use Fraction(str(number)) for more accurate results due to + float inaccuracies. + + :return: + The continued fraction of rational number. + It is the all commas in the (n + 1)-tuple notation. + + >>> continued_fraction(Fraction(2)) + [2] + >>> continued_fraction(Fraction("3.245")) + [3, 4, 12, 4] + >>> continued_fraction(Fraction("2.25")) + [2, 4] + >>> continued_fraction(1/Fraction("2.25")) + [0, 2, 4] + >>> continued_fraction(Fraction("415/93")) + [4, 2, 6, 7] + """ + numerator, denominator = num.as_integer_ratio() + continued_fraction_list: list[int] = [] + while True: + integer_part = int(numerator / denominator) + continued_fraction_list.append(integer_part) + numerator -= integer_part * denominator + if numerator == 0: + break + numerator, denominator = denominator, numerator + + return continued_fraction_list + + +if __name__ == "__main__": + import doctest + + doctest.testmod() + + print("Continued Fraction of 0.84375 is: ", continued_fraction(Fraction("0.84375")))