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

Sympy绘制Sum表达式时变量n未自动替换的问题求解

问题分析与解决方案

问题原因

当你调用N(r)时,r是包含符号变量n的求和表达式,SymPy会将其视为无穷级数的极限(因n未指定具体值),直接计算出自然常数e≈2.71828。因此plot(N(r), (n,0,10))本质是绘制一条等于e的水平线,而非级数的部分和序列。

解决方案

方案1:使用匿名函数逐个代入求值

利用SymPy的plot支持匿名函数的特性,在每个采样点手动替换n并计算数值:

from sympy import init_printing, plot, symbols
from sympy import Sum, factorial, N

init_printing()
i, n = symbols('i n', integer=True)
r = Sum(1/factorial(i), (i,0,n))

# 传入匿名函数,对每个x(n的取值)转整数后代入计算
plot(lambda x: N(r.subs(n, int(x))), (n, 0, 10), discrete=True)

discrete=True参数会让绘图显示离散点与连线,更贴合整数n对应的级数部分和特性。

方案2:转换为数值函数后绘图

用lambdify将符号表达式转为可批量计算的函数,再结合Matplotlib实现更灵活的可视化:

from sympy import init_printing, symbols, Sum, factorial, N, lambdify
import matplotlib.pyplot as plt

init_printing()
i, n = symbols('i n', integer=True)
r = Sum(1/factorial(i), (i,0,n))

# 转换为可接收数值输入的函数
r_func = lambdify(n, N(r.subs(n, n)))

# 生成n的整数取值范围
n_vals = list(range(0, 11))
y_vals = [r_func(k) for k in n_vals]

# 绘制离散点与趋势线
plt.scatter(n_vals, y_vals, label='Partial Sum')
plt.plot(n_vals, y_vals, linestyle='--', alpha=0.7)
plt.xlabel('n')
plt.ylabel(r'$\sum_{i=0}^n \frac{1}{i!}$')
plt.title('Partial Sums of the Exponential Series')
plt.legend()
plt.show()

补充说明

级数$\sum_{i=0}^n \frac{1}{i!}$是自然常数e的泰勒展开前n+1项部分和,随着n增大,结果会快速收敛到e,这也是你在n=10时得到的值接近e的原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:35:31