如何从Sympy的NotImplementedError报错中提取cos(x)这类指定内容
提取Sympy求解报错中生成器项的实现方案
场景复现
你使用的原有Sympy求解代码如下:
from sympy.solvers import solve from sympy import Symbol, sympify x = Symbol('x') function = sympify(input("Insert function: ")) # 原有代码缺少字符串转Sympy表达式的步骤,此处补充修正 def gx(function,x): return solve(function,x,dict=True) print(gx(function,x))
输入cos(x)+x时触发的报错为:
NotImplementedError: multiple generators [x, cos(x)] No algorithms are implemented to solve equation x + cos(x)
实现方法
方案1:解析报错字符串提取
直接捕获报错信息,对固定格式的报错内容做切片提取,实现简单:
from sympy.solvers import solve from sympy import Symbol, sympify x = Symbol('x') function = sympify(input("Insert function: ")) def gx(function,x): try: return solve(function,x,dict=True) except NotImplementedError as e: err = str(e) if "multiple generators" not in err: raise e # 截取[]区间内的生成器列表 gen_str = err.split("[")[1].split("]")[0] gen_list = [item.strip() for item in gen_str.split(",")] # 过滤掉变量x,保留其他生成器项 target_terms = [t for t in gen_list if t != str(x)] return {"提取到的非变量生成器": target_terms} print(gx(function,x))
输入cos(x)+x运行后输出为:{'提取到的非变量生成器': ['cos(x)']}
方案2:直接从表达式提取(更稳定)
不依赖报错格式,用Sympy内置方法遍历表达式原子项,提取目标超越函数:
from sympy import FunctionClass def extract_transcendental_terms(expr, var): res = [] for atom in expr.atoms(): # 筛选包含目标变量的函数项 if isinstance(atom.__class__, FunctionClass) and var in atom.atoms(): res.append(str(atom)) return res # 调用示例,输入为cos(x)+x时返回['cos(x)'] print("提取到的超越函数项:", extract_transcendental_terms(function, x))
内容的提问来源于stack exchange,提问作者Raúl Peñate
相关产品推荐
相关产品推荐

