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

如何在SymPy中提取含大O项的级数展开式的系数?

提取SymPy级数展开式的幂次系数

解决方法

由于sp.Poly仅支持整数次幂的多项式,无法处理负幂、分数幂及大O项,因此可以直接拆分表达式的每一项,逐个解析系数与幂次:

import sympy as sp

x = sp.Symbol("x")
expr = 1/x + 2*x + 3*x**(3/2) + 4*x**2 + sp.O(x**3)

# 拆分表达式为单独项并过滤大O项
terms = [term for term in expr.as_ordered_terms() if not isinstance(term, sp.Order)]

# 构建系数-幂次字典
coeff_dict = {}
for term in terms:
    # 拆分系数与x的幂次
    coeff, power = sp.expand_power_base(term).as_coeff_exponent(x)
    # 将SymPy的有理/整数幂转为浮点数
    power_float = float(power) if isinstance(power, (sp.Rational, sp.Integer)) else power
    coeff_float = float(coeff)
    coeff_dict[power_float] = coeff_float

print(coeff_dict)

代码说明

  • expr.as_ordered_terms():将表达式拆分为独立项的列表,包含大O项
  • 过滤sp.Order类型的元素,移除大O项
  • sp.expand_power_base(term).as_coeff_exponent(x):将每一项拆解为系数和x的幂次,例如1/x会被拆分为(1, -1),3*x**(3/2)拆分为(3, 3/2)
  • 将SymPy的符号数转为普通浮点数,匹配目标字典的格式

运行代码后将输出:

{-1.0: 1.0, 1.0: 2.0, 1.5: 3.0, 2.0: 4.0}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:35:29