我正在尝试使用 sympy 并处理表达式的操作。
import sympy as sym
from sympy.abc import t
x0,v0 = sym.symbols("x0 v0 ", real=True)
wn = sym.symbols("omega_n", positive = True, real=True)
z = sym.symbols("zeta", positive = True, real=True)
x = sym.Function('x')
Dx = sym.Derivative(x(t), t)
Dx2= sym.Derivative(x(t), t,2)
res = sym.dsolve(Dx2 +2*z*wn*Dx+ wn**2*x(t), x(t),
ics = { x(0): x0,
Dx.subs(t,0):v0})
上面的结果是下面的表达式
红圈部分可以进一步简化为 ,但是我不知道如何简化表达式的选定部分。
如果我采用一个更简单的示例wn*x0*z**2/(2*wn*z**2-2*wn)
,那么可以使用简化( ),但我可以在任何地方找到一些关于如何工作和替换方程部分的好文档。
最佳答案
一种方法是使用模式匹配。请注意,圈出的术语是乘法,包含 z**2
(幂运算)。
# search the expression tree and select all multiplications
# containing a power with exponent 2
w = sym.Wild("w", properties=[
lambda e: e.is_Mul and any(t.is_Pow and t.exp == 2 for t in e.args)
])
t = list(res.find(w))[0]
print(t)
# out: omega_n*x0*zeta**2/(2*omega_n*zeta**2 - 2*omega_n)
# Perform the simplification and substitution
res = res.subs(t, t.simplify())
现在让我们查找问题中的第二个术语:
# loop over each exponential term and apply a
# powsimp to its argument.
for t in res.find(sym.exp):
res = res.subs(t, sym.exp(t.args[0].powsimp()))
print(res)
编辑:类似地,您可以应用相同的技术来简化表达式中的其他平方根。
关于python - sympy 表达式的精细操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74574539/