take the derivative of a function in python

To take the derivative of a function in Python, you can use either of the following methods:

  1. Using SymPy library
  2. Using NumPy library

Here's an example to take the derivative of a function using SymPy:

main.py
import sympy as sym

# define the function
x = sym.Symbol('x')
f = x**3 + 2*x - 1

# take the derivative
f_prime = sym.diff(f, x)

# print the result
print(f_prime)
165 chars
12 lines

Output:

main.py
3*x**2 + 2
11 chars
2 lines

Here's another example to take the derivative of a function using NumPy:

main.py
import numpy as np

# define the function
def f(x):
    return x**3 + 2*x - 1

# define the interval
x = np.linspace(-10, 10, 1000)

# take the derivative
f_prime = np.gradient(f(x), x)

# plot the result
import matplotlib.pyplot as plt
plt.plot(x, f_prime)
plt.xlabel('x')
plt.ylabel('f\'(x)')
plt.show()
306 chars
19 lines

Output: A plot of the derivative of the function.

gistlibby LogSnag