在 Sympy 中是否有规范的方法来声明函数?我尝试过
import sympy
import sympy.functions.special.delta_functions as special
sympy.init_printing()
x = sympy.symbols('x', real=True)
V = x*x * (special.Heaviside(x + 1) - special.Heaviside(x - 1)) \
+ (1 + 2*sympy.log(x)) * special.Heaviside(x - 1) \
+ (1 + 2*sympy.log(-x)) * special.Heaviside(-x - 1)
定义了一个微分函数,但是
print(V.diff(x).simplify())
# Prints: (x*(x**2*(-DiracDelta(x - 1) + DiracDelta(x + 1)) - 2*x*(Heaviside(x - 1) - Heaviside(x + 1)) - (2*log(-x) + 1)*DiracDelta(x + 1) + (2*log(x) + 1)*DiracDelta(x - 1)) + 2*Heaviside(-x - 1) + 2*Heaviside(x - 1))/x
是否可以通过某种方式告诉 Sympy 将DiracDelta(x - a)*f(x)
简化为DiracDelta(x - a)*f(a)
?
答案 0 :(得分:2)
逐个定义的函数由Piecewise类实现。您的函数将表示为
V = sympy.Piecewise((1 + 2*sympy.log(-x), x < -1),
(x**2, x < 1),
(1 + 2*sympy.log(x), True))
print(V.diff(x))
显示Piecewise((2/x, x < -1), (2*x, x < 1), (2/x, True))
(expr, cond)
中的Piecewise
对将按照给定的顺序进行处理:第一个评估为True的cond
(如果前面的评估为False)会导致相应的expr
退回。