Search code examples
pythonsympyderivativedifferentiation

How to differentiate a expression with respect to a symbol that is not a free symbol of the expression in SymPy?


I have the following equation, like this:

y = 3x2 + x

Then, I want to differentiate the both side w.r.t the variable t with sympy. I try to implement it in the following code in JupyterNotebook:

>>> import sympy as sp
>>> x, y, t = sp.symbols('x y t', real=True)
>>> eq = sp.Eq(y, 3 * x **2 + x)
>>>
>>> expr1 = eq.lhs
>>> expr1
𝑦
>>> expr1.diff(t)
0
>>>
>>> expr2 = eq.rhs
>>> expr2
3𝑥^2+𝑥
>>> expr2.diff(t)
0

As the result, sympy will treat the symbol x and y as a constant. However, the ideal result I want should be the same as the result derived manually like this:

y = 3x2 + x

d/dt (y) = d/dt (3x2 + x)

dy/dt = 6 • x • dx/dt + 1 • dx/dt

dy/dt = (6x + 1) • dx/dt

How can I do the derivative operation on a expression with a specific symbol which is not a free symbol in the expression?


Solution

  • You should declare x and y as functions rather than symbols e.g.:

    In [8]: x, y = symbols('x, y', cls=Function)
    
    In [9]: t = symbols('t')
    
    In [10]: eq = Eq(y(t), 3*x(t)**2 + x(t))
    
    In [11]: eq
    Out[11]: 
              2          
    y(t) = 3⋅x (t) + x(t)
    
    In [12]: Eq(eq.lhs.diff(t), eq.rhs.diff(t))
    Out[12]: 
    d                 d          d       
    ──(y(t)) = 6⋅x(t)⋅──(x(t)) + ──(x(t))
    dt                dt         dt  
    

    https://docs.sympy.org/latest/modules/core.html#sympy.core.function.Function