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?
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