SymPy – Derivative

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 −

xsin(x2)+1

>>> diff(expr,x)

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

2x2cos(x2)+sin(x2)

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

24x24x

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

2x2cos(x2)+sin(x2)

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 −

d/dx(xsin(x2)+1)

>>> d.doit()

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

2x2cos(x2)+sin(x2)

This Post Has 2 Comments

Leave a Reply