Search code examples
pythonpython-3.xsympysymbolic-math

Differential equation solution not shown by SymPy


In the following code, I first solve a differential equation, but, then, when I check to see if it is a solution, it appears not to be. (The following code returns False.) What am I doing wrong?

import sympy as sy

t = sy.symbols('t')
y = sy.symbols('y', cls=sy.Function)

expr = y(t).diff(t, t) + 3*y(t).diff(t) + 2*y(t) - 4*t
solution = sy.dsolve(sy.Eq(expr, 0)).rhs

print(expr.subs(y(t), solution).simplify() == 0)


Solution

  • You need doit() to effectively evaluate the derivative: expr.subs(y(t), solution).doit()

    import sympy as sy
    
    t = sy.symbols('t')
    y = sy.symbols('y', cls=sy.Function)
    
    expr = y(t).diff(t, t) + 3*y(t).diff(t) + 2*y(t) - 4*t
    solution = sy.dsolve(sy.Eq(expr, 0)).rhs
    
    print(expr.subs(y(t), solution).doit().simplify() == 0)
    

    Prints True