如何在Python中将分数转换为连分数?
Fraction Module Got it, I see you're trying to convert a fraction like 181/101 into its continued fraction coefficients (which should be 1 1 3 1 4 4), but you struggled to adapt code using the Fraction module. Let's break this down step by step.
How Continued Fractions Work
For any fraction a/b, the process to get coefficients is:
- Take the integer part
q = a // b(this is your next coefficient) - Calculate the remainder
r = a % b - If
ris 0, we're done. Otherwise, repeat the process with the fractionb/r - Collect all the
qvalues to get your sequence
Using the Fraction Module
The Fraction module simplifies handling fractions by automatically managing numerators and denominators, so we don't have to deal with manual simplification. Here's a working implementation:
from fractions import Fraction def get_continued_fraction_coefficients(fraction): coefficients = [] while True: # Extract the integer part of the fraction integer_part = fraction.numerator // fraction.denominator coefficients.append(integer_part) # Calculate remainder after removing the integer part remainder = fraction.numerator % fraction.denominator if remainder == 0: break # Update the fraction to be the reciprocal of the remaining fractional part fraction = Fraction(fraction.denominator, remainder) return coefficients # Test with your example input input_fraction = Fraction(181, 101) result = get_continued_fraction_coefficients(input_fraction) print(' '.join(map(str, result))) # Output: 1 1 3 1 4 4
Adapting to Your Inputs
If you're starting with a string like "181/101" instead of a Fraction object, you can parse it easily:
input_str = "181/101" num, den = map(int, input_str.split('/')) input_fraction = Fraction(num, den)
Key Notes
- The
Fractionmodule handles all simplification for you, so even if your input fraction isn't in lowest terms (like 362/202), it'll still produce the correct coefficients. - For integer inputs (like
Fraction(5,1)), the function will return just[5], which is the correct continued fraction representation.
Let me know if you need any tweaks to fit your specific use case!
内容的提问来源于stack exchange,提问作者Marked as Duplicate

