Calculating Derivatives of a Function in Python

To compute the first, second, and third derivatives of a function in Python, you can use the diff() function from the SymPy library, which is designed for symbolic mathematics.

diff(f, x, n)

Here, f is the function to differentiate, x is the variable, and n is the order of the derivative.

Below is a complete example of Python code to calculate the first, second, and third derivatives of a function.

First, import the SymPy library:

import sympy as sp

Next, define the symbol for the variable you want to differentiate:

x = sp.symbols('x')

Then, define the function:

f = x**4 + 3*x**3 + 2*x**2 + x + 1

Now, you can proceed with calculating the derivatives.

Use sp.diff(f, x) to calculate the first derivative of the function:

f_prime = sp.diff(f, x)

By default, sp.diff computes the first derivative if the order is not specified.

The result is the first derivative of f(x):

print(f_prime)

4*x**3 + 9*x**2 + 4*x + 1

To calculate the second derivative, differentiate the first derivative:

The second derivative, f''(x), is the derivative of the first derivative, f'(x):

f_second = sp.diff(f_prime, x)
print(f_second)

12*x**2 + 18*x + 4

Alternatively, you can calculate the second derivative directly from the original function by specifying the order as 2, which is often the preferred method:

The result is the same:

f_second = sp.diff(f, x, 2)
print(f_second)

12*x**2 + 18*x + 4

Similarly, you can compute the third derivative:

f_third = sp.diff(f, x, 3)
print(f_third)

24*x + 18

You have now calculated the first, second, and third derivatives of the function f(x).

The same process can be used to find the fourth, fifth, or any higher-order derivative of any function.

And so on.

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Sympy