SymPy - Derivative


Advertisements

The derivative of a function is its instantaneous rate of change with respect to one of its variables. This is equivalent to finding the slope of the tangent line to the function at a point.we can find the differentiation of mathematical expressions in the form of variables by using diff() function in SymPy package.

diff(expr, variable)
>>> from sympy import diff, sin, exp 
>>> from sympy.abc import x,y 
>>> expr=x*sin(x*x)+1 >>> expr

The above code snippet gives an output equivalent to the below expression −

$x\sin(x^2) + 1$

>>> diff(expr,x)

The above code snippet gives an output equivalent to the below expression −

$2x^2\cos(x^2) + \sin(x^2)$

>>> diff(exp(x**2),x)

The above code snippet gives an output equivalent to the below expression −

2xex2

To take multiple derivatives, pass the variable as many times as you wish to differentiate, or pass a number after the variable.

>>> diff(x**4,x,3)

The above code snippet gives an output equivalent to the below expression −

$24x$

>>> for i in range(1,4): print (diff(x**4,x,i))

The above code snippet gives the below expression −

4*x**3

12*x**2

24*x

It is also possible to call diff() method of an expression. It works similarly as diff() function.

>>> expr=x*sin(x*x)+1 
>>> expr.diff(x)

The above code snippet gives an output equivalent to the below expression −

$2x^2\cos(x^2) + \sin(x^2)$

An unevaluated derivative is created by using the Derivative class. It has the same syntax as diff() function. To evaluate an unevaluated derivative, use the doit method.

>>> from sympy import Derivative 
>>> d=Derivative(expr) 
>>> d

The above code snippet gives an output equivalent to the below expression −

$\frac{d}{dx}(x\sin(x^2)+1)$

>>> d.doit()

The above code snippet gives an output equivalent to the below expression −

$2x^2\cos(x^2) + \sin(x^2)$

Advertisements