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

Taylor级数近似程序异常求助:自定义函数近似值错误收敛

问题分析与修复方案

核心错误点

  • 泰勒近似未逐点重置:代码中n和approx仅在程序开头初始化一次,遍历每个x时未重新归零。这导致只有第一个x会计算完整的泰勒级数,后续所有x的近似值要么基于第一个x的累加结果继续叠加,要么因n超过order完全不更新,最终收敛到错误数值。
  • 阶数类型错误:输入的order被转为float,但泰勒级数阶数必须是整数,应转为int类型避免隐式类型问题。

修复后的代码

import math
import matplotlib.pyplot as plt
import numpy as np

# 将阶数转为整数类型
order = int(input("Enter the Taylor series approximation order (n):  "))
file_object = open("taylor.dat", "w")
x = -2 * np.pi
taylor_list = []

def func(x):
    fx = np.sin(x) * np.exp(-x/2)
    return fx

def deriv(n):
    nth = ((-(math.sqrt(5))/2)**n) * np.sin(-n * np.arctan(2))
    return nth

def taylor(x, n):
    tx = (deriv(n) / np.math.factorial(n)) * (x**n)
    return tx

while x <= 2 * np.pi:
    # 每个x点重新初始化近似值和阶数计数器
    approx = 0
    n = 0
    file_object.write(str(round(x, 10)))
    file_object.write(" ")
    fx = func(x)
    file_object.write(str(round(fx, 10)))
    file_object.write(" ")
    # 对当前x计算从n=0到order的所有项累加
    while n <= order:
        tx = taylor(x, n)
        approx += tx
        n += 1
    file_object.write(str(round(approx, 10)))
    file_object.write("\n")
    taylor_list.append(approx)
    x += (1/25)*np.pi

file_object.close()

# 补充绘图代码用于验证
x_vals = np.arange(-2*np.pi, 2*np.pi + (1/25)*np.pi, (1/25)*np.pi)
plt.plot(x_vals, [func(x) for x in x_vals], label='Exact Value')
plt.plot(x_vals, taylor_list, label=f'Taylor Approx (order {order})', linestyle='--')
plt.legend()
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Taylor Series Approximation vs Exact Function')
plt.show()

额外说明

  • 原代码中deriv函数的导数计算逻辑正确,验证前几阶导数在x=0处的结果与手动计算一致,无需修改。
  • 修复后每个x点都会重新计算完整的泰勒级数累加和,近似值会在收敛区间内与精确值匹配。

内容的提问来源于stack exchange,提问作者Thotscar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:48:19