🛠️ToolsShed

泰勒级数计算器

计算sin、cos、exp、ln等函数的泰勒/麦克劳林级数近似。

Series Formula

sin(x) = x - x³/3! + x⁵/5! - x⁷/7! + ...

常见问题

代码实现

import math

def factorial(n: int) -> int:
    return math.factorial(n)

def taylor_sin(x: float, n_terms: int) -> list[float]:
    """sin(x) = sum(-1)^n * x^(2n+1) / (2n+1)!"""
    terms = []
    partial_sum = 0
    for n in range(n_terms):
        term = ((-1)**n * x**(2*n+1)) / factorial(2*n+1)
        partial_sum += term
        terms.append({'n': n, 'term': term, 'partial_sum': partial_sum})
    return terms

def taylor_exp(x: float, n_terms: int) -> list[float]:
    """e^x = sum x^n / n!"""
    terms = []
    partial_sum = 0
    for n in range(n_terms):
        term = x**n / factorial(n)
        partial_sum += term
        terms.append({'n': n, 'term': term, 'partial_sum': partial_sum})
    return terms

def taylor_cos(x: float, n_terms: int) -> list[float]:
    """cos(x) = sum(-1)^n * x^(2n) / (2n)!"""
    terms = []
    partial_sum = 0
    for n in range(n_terms):
        term = ((-1)**n * x**(2*n)) / factorial(2*n)
        partial_sum += term
        terms.append({'n': n, 'term': term, 'partial_sum': partial_sum})
    return terms

# Example: sin(0.5)
x = 0.5
n_terms = 6
result = taylor_sin(x, n_terms)
approx = result[-1]['partial_sum']
exact = math.sin(x)
print(f"sin({x}) approximation with {n_terms} terms:")
for r in result:
    print(f"  n={r['n']}: term={r['term']:.8f}, sum={r['partial_sum']:.10f}")
print(f"Exact: {exact:.10f}")
print(f"Error: {abs(approx - exact):.2e}")

Comments & Feedback

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