🛠️ToolsShed

连分数计算器

将小数或分数转换为连分数表示和收敛分数。

常见问题

代码实现

import math

def continued_fraction(x: float, max_terms: int = 20) -> list[int]:
    """Compute continued fraction representation of x"""
    terms = []
    remaining = x
    for _ in range(max_terms):
        a = int(math.floor(remaining))
        terms.append(a)
        frac = remaining - a
        if abs(frac) < 1e-10:
            break
        remaining = 1 / frac
        if not math.isfinite(remaining):
            break
    return terms

def convergents(terms: list[int]) -> list[tuple[int, int]]:
    """Compute convergents (rational approximations) from continued fraction terms"""
    conv = []
    h_prev, h_curr = 1, terms[0]
    k_prev, k_curr = 0, 1
    conv.append((h_curr, k_curr))

    for i in range(1, len(terms)):
        a = terms[i]
        h_next = a * h_curr + h_prev
        k_next = a * k_curr + k_prev
        h_prev, h_curr = h_curr, h_next
        k_prev, k_curr = k_curr, k_next
        conv.append((h_curr, k_curr))
    return conv

# Example: pi
pi_terms = continued_fraction(math.pi, 10)
print(f"pi = [{pi_terms[0]}; {', '.join(map(str, pi_terms[1:]))}]")

for num, den in convergents(pi_terms):
    approx = num / den
    error = abs(approx - math.pi)
    print(f"  {num}/{den} = {approx:.10f}  (error: {error:.2e})")

# Golden ratio
phi = (1 + math.sqrt(5)) / 2
print(f"phi terms: {continued_fraction(phi, 8)}")  # All ones!

# sqrt(2)
sqrt2_terms = continued_fraction(math.sqrt(2), 8)
print(f"sqrt(2) terms: {sqrt2_terms}")  # [1; 2, 2, 2, ...]

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.