File tree Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change 555555 * [ Chudnovsky Algorithm] ( maths/chudnovsky_algorithm.py )
556556 * [ Collatz Sequence] ( maths/collatz_sequence.py )
557557 * [ Combinations] ( maths/combinations.py )
558+ * [ Continued Fraction] ( maths/continued_fraction.py )
558559 * [ Decimal Isolate] ( maths/decimal_isolate.py )
559560 * [ Decimal To Fraction] ( maths/decimal_to_fraction.py )
560561 * [ Dodecahedron] ( maths/dodecahedron.py )
Original file line number Diff line number Diff line change 1+ """
2+ Finding the continuous fraction for a rational number using python
3+
4+ https://en.wikipedia.org/wiki/Continued_fraction
5+ """
6+
7+
8+ from fractions import Fraction
9+
10+
11+ def continued_fraction (num : Fraction ) -> list [int ]:
12+ """
13+ :param num:
14+ Fraction of the number whose continued fractions to be found.
15+ Use Fraction(str(number)) for more accurate results due to
16+ float inaccuracies.
17+
18+ :return:
19+ The continued fraction of rational number.
20+ It is the all commas in the (n + 1)-tuple notation.
21+
22+ >>> continued_fraction(Fraction(2))
23+ [2]
24+ >>> continued_fraction(Fraction("3.245"))
25+ [3, 4, 12, 4]
26+ >>> continued_fraction(Fraction("2.25"))
27+ [2, 4]
28+ >>> continued_fraction(1/Fraction("2.25"))
29+ [0, 2, 4]
30+ >>> continued_fraction(Fraction("415/93"))
31+ [4, 2, 6, 7]
32+ """
33+ numerator , denominator = num .as_integer_ratio ()
34+ continued_fraction_list : list [int ] = []
35+ while True :
36+ integer_part = int (numerator / denominator )
37+ continued_fraction_list .append (integer_part )
38+ numerator -= integer_part * denominator
39+ if numerator == 0 :
40+ break
41+ numerator , denominator = denominator , numerator
42+
43+ return continued_fraction_list
44+
45+
46+ if __name__ == "__main__" :
47+ import doctest
48+
49+ doctest .testmod ()
50+
51+ print ("Continued Fraction of 0.84375 is: " , continued_fraction (Fraction ("0.84375" )))
You can’t perform that action at this time.
0 commit comments