Skip to content

Added Continued fractions #6846

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
51 changes: 51 additions & 0 deletions maths/continued_fraction.py
Original file line number Diff line number Diff line change
@@ -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]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs tests for 0 and for negative numbers.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added tests for 0 and negative numbers in #8985

"""
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")))