From e887c14f1252cd7de3d99ef0553c448c8c9711df Mon Sep 17 00:00:00 2001 From: Tianyi Zheng Date: Fri, 18 Aug 2023 13:53:17 -0700 Subject: [PATCH] Fix continued_fraction.py to work for negative numbers (#8985) * Add doctests to continued_fraction.py for 0 and neg nums * Fix continued_fraction.py to work for negative nums Fix continued_fraction.py to work for negative nums by replacing int() call with floor() * Move comment in doctest --- maths/continued_fraction.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/maths/continued_fraction.py b/maths/continued_fraction.py index 25ff649db..04ff0b6ff 100644 --- a/maths/continued_fraction.py +++ b/maths/continued_fraction.py @@ -6,6 +6,7 @@ https://en.wikipedia.org/wiki/Continued_fraction from fractions import Fraction +from math import floor def continued_fraction(num: Fraction) -> list[int]: @@ -29,11 +30,17 @@ def continued_fraction(num: Fraction) -> list[int]: [0, 2, 4] >>> continued_fraction(Fraction("415/93")) [4, 2, 6, 7] + >>> continued_fraction(Fraction(0)) + [0] + >>> continued_fraction(Fraction(0.75)) + [0, 1, 3] + >>> continued_fraction(Fraction("-2.25")) # -2.25 = -3 + 0.75 + [-3, 1, 3] """ numerator, denominator = num.as_integer_ratio() continued_fraction_list: list[int] = [] while True: - integer_part = int(numerator / denominator) + integer_part = floor(numerator / denominator) continued_fraction_list.append(integer_part) numerator -= integer_part * denominator if numerator == 0: