You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将分数转换为连分数?

Converting a Fraction to Continued Fraction Coefficients with Python's 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 r is 0, we're done. Otherwise, repeat the process with the fraction b/r
  • Collect all the q values 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 Fraction module 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:06:56