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

SymPy参数化复数问题:输出含re()/im()的原因及解决方法

问题描述

现有如下Python代码:

import sympy as sp

t = sp.symbols('t', real=True)

y = sp.parse_expr(input("y = "))
real_imag = y.as_real_imag()
print("Real:", real_imag[0])
print("Imaginary:", real_imag[1])

当输入表达式为"t**2 + t*I"时,当前输出为:

Real: re(t)**2 - im(t)**2 - im(t)
Imaginary: 2*re(t)*im(t) + re(t)

但期望输出应为:

Real: t**2
Imaginary: t

需求要求必须保留用户输入环节,且输出结果不能包含re()和im()函数。已尝试用re()/im()替代as_real_imag()、sympify()替代parse_expr()、调用simplify()和expand()方法,均无效果,需解决该问题。

解决方案

问题核心是parse_expr默认不会关联已定义的符号t及其real=True属性,导致输入里的t被当作新的未定义符号处理,SymPy无法确定其为实数,只能用re()/im()表示实虚部。只需在parse_expr调用时传入locals参数,让解析器识别已定义的实变量t即可。

修改后的代码示例:

import sympy as sp

t = sp.symbols('t', real=True)

# 传入locals参数,关联已定义的实变量t
y = sp.parse_expr(input("y = "), locals={"t": t})
real_part, imag_part = y.as_real_imag()
print("Real:", real_part)
print("Imaginary:", imag_part)

也可以直接用sp.re()和sp.im()获取实虚部,效果一致:

import sympy as sp

t = sp.symbols('t', real=True)

y = sp.parse_expr(input("y = "), locals={"t": t})
print("Real:", sp.re(y))
print("Imaginary:", sp.im(y))

输入"t**2 + t*I"时,两种写法都会输出期望结果:

Real: t**2
Imaginary: t

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 01:15:58