MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / continued_fraction

Function continued_fraction

maths/continued_fraction.py:11–49  ·  view source on GitHub ↗

: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. >>> cont

(num: Fraction)

Source from the content-addressed store, hash-verified

9
10
11def 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 >>> continued_fraction(Fraction(0))
33 [0]
34 >>> continued_fraction(Fraction(0.75))
35 [0, 1, 3]
36 >>> continued_fraction(Fraction("-2.25")) # -2.25 = -3 + 0.75
37 [-3, 1, 3]
38 """
39 numerator, denominator = num.as_integer_ratio()
40 continued_fraction_list: list[int] = []
41 while True:
42 integer_part = floor(numerator / denominator)
43 continued_fraction_list.append(integer_part)
44 numerator -= integer_part * denominator
45 if numerator == 0:
46 break
47 numerator, denominator = denominator, numerator
48
49 return continued_fraction_list
50
51
52if __name__ == "__main__":

Callers 1

Calls 2

floorFunction · 0.90
appendMethod · 0.45

Tested by

no test coverage detected