mirror of
https://hub.njuu.cf/TheAlgorithms/Python.git
synced 2023-10-11 13:06:12 +08:00
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
This commit is contained in:
parent
945803f65d
commit
e887c14f12
@ -6,6 +6,7 @@ https://en.wikipedia.org/wiki/Continued_fraction
|
|||||||
|
|
||||||
|
|
||||||
from fractions import Fraction
|
from fractions import Fraction
|
||||||
|
from math import floor
|
||||||
|
|
||||||
|
|
||||||
def continued_fraction(num: Fraction) -> list[int]:
|
def continued_fraction(num: Fraction) -> list[int]:
|
||||||
@ -29,11 +30,17 @@ def continued_fraction(num: Fraction) -> list[int]:
|
|||||||
[0, 2, 4]
|
[0, 2, 4]
|
||||||
>>> continued_fraction(Fraction("415/93"))
|
>>> continued_fraction(Fraction("415/93"))
|
||||||
[4, 2, 6, 7]
|
[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()
|
numerator, denominator = num.as_integer_ratio()
|
||||||
continued_fraction_list: list[int] = []
|
continued_fraction_list: list[int] = []
|
||||||
while True:
|
while True:
|
||||||
integer_part = int(numerator / denominator)
|
integer_part = floor(numerator / denominator)
|
||||||
continued_fraction_list.append(integer_part)
|
continued_fraction_list.append(integer_part)
|
||||||
numerator -= integer_part * denominator
|
numerator -= integer_part * denominator
|
||||||
if numerator == 0:
|
if numerator == 0:
|
||||||
|
Loading…
Reference in New Issue
Block a user