Jet C.
Jet C.

Reputation: 176

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?

Upvotes: 0

Views: 873

Answers (2)

smichr
smichr

Reputation: 19093

Alternatively, the idiff function was made for this purpose but it works with expressions like f(x, y) and can return the value of dy/dx. So first make your Eq and expression and then calculate the desired derivative:

>>> from sympy import idiff
>>> e = eq.rewrite(Add)
>>> dydx = idiff(e, y, x); dydx
6*x + 1

Note, too, that even in your equation (if you write it explicitly in terms of functions of t) you do not need to isolate y(t) -- you can differentiate and solve for it:

>>> from sympy.abc import t
>>> x,y=map(Function,'xy')
>>> eq = x(t)*(y(t)**2 - y(t) + 1)
>>> yp=y(t).diff(t); Eq(yp, solve(eq.diff(t),yp)[0])
Eq(Derivative(y(t), t), (-y(t)**2 + y(t) - 1)*Derivative(x(t), t)/((2*y(t) - 1)*x(t)))

Upvotes: 0

Oscar Benjamin
Oscar Benjamin

Reputation: 14500

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

Upvotes: 2

Related Questions