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

Python实现arctan(x)带绘图功能及自定义函数返回值异常排查

修正Arctan函数并实现绘图功能

原函数的问题分析

  • return语句缩进错误:原代码中return s写在for循环内部,导致第一次循环(i=0)就直接返回结果,后续迭代完全没执行。
  • 级数项计算错误:原代码的series=(X**((2*i)+1))/2*i+1运算顺序错误,正确的泰勒级数项应为$\frac{x^{2i+1}}{2i+1}$,需要给分母2*i+1加上括号,否则会先做除法再乘法再加1,完全偏离正确公式。

修正后的Arctan函数

结合泰勒级数的收敛特性(仅在$|x| \leq 1$时收敛),补充对$|x| > 1$的情况处理,利用恒等式扩展适用范围:

  • 当$x > 1$时,$\arctan(x) = \frac{\pi}{2} - \arctan(\frac{1}{x})$
  • 当$x < -1$时,$\arctan(x) = -\frac{\pi}{2} - \arctan(\frac{1}{x})$

修正后的代码:

import math

def Arctan(X: float, n: int = 50):
    # 处理|x| > 1的情况,扩展级数适用范围
    if abs(X) > 1:
        return math.copysign(math.pi / 2, X) - Arctan(1 / X, n)
    s = 0.0
    for i in range(n):
        flag = (-1) ** i
        # 正确计算泰勒级数项
        series = (X ** (2 * i + 1)) / (2 * i + 1)
        s += flag * series
    return s

绘图功能实现

使用matplotlib绘制自定义Arctan函数与标准库math.atan的对比曲线,验证正确性:

import matplotlib.pyplot as plt
import numpy as np

# 生成x轴数据,范围从-3到3,取1000个点
x = np.linspace(-3, 3, 1000)
# 计算自定义函数和标准函数的结果
y_custom = [Arctan(x_val) for x_val in x]
y_standard = [math.atan(x_val) for x_val in x]

# 设置绘图样式
plt.figure(figsize=(10, 6))
plt.plot(x, y_custom, label='自定义Arctan函数', linestyle='--', alpha=0.8)
plt.plot(x, y_standard, label='math.atan标准函数', linewidth=1, alpha=0.8)
plt.xlabel('x')
plt.ylabel('arctan(x)')
plt.title('自定义Arctan函数与标准函数对比')
plt.legend()
plt.grid(True, linestyle=':', alpha=0.5)
plt.show()

说明

  • 迭代次数n默认设为50,相比原代码的10次,能提升计算精度,尤其是在x接近1或-1时。
  • 扩展了$|x| > 1$的处理逻辑,解决了泰勒级数仅在$|x| \leq 1$收敛的限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 11:45:22