You have four options

  1. Finite Differences
  2. Automatic Derivatives
  3. Symbolic Differentiation
  4. Compute derivatives by hand.

Finite differences require no external tools but are prone to numerical error and, if you're in a multivariate situation, can take a while.

Symbolic differentiation is ideal if your problem is simple enough. Symbolic methods are getting quite robust these days. SymPy is an excellent project for this that integrates well with NumPy. Look at the autowrap or lambdify functions or check out Jensen's blogpost about a similar question.

Automatic derivatives are very cool, aren't prone to numeric errors, but do require some additional libraries (google for this, there are a few good options). This is the most robust but also the most sophisticated/difficult to set up choice. If you're fine restricting yourself to numpy syntax then Theano might be a good choice.

Here is an example using SymPy

In [1]: from sympy import *
In [2]: import numpy as np
In [3]: x = Symbol('x')
In [4]: y = x**2 + 1
In [5]: yprime = y.diff(x)
In [6]: yprime
Out[6]: 2⋅x

In [7]: f = lambdify(x, yprime, 'numpy')
In [8]: f(np.ones(5))
Out[8]: [ 2.  2.  2.  2.  2.]
Answer from MRocklin on Stack Overflow
🌐
Derivative Calculator
derivative-calculator.net
Derivative Calculator • With Steps!
Solve derivatives using this free online calculator. Step-by-step solution and graphs included!
Top answer
1 of 9
208

You have four options

  1. Finite Differences
  2. Automatic Derivatives
  3. Symbolic Differentiation
  4. Compute derivatives by hand.

Finite differences require no external tools but are prone to numerical error and, if you're in a multivariate situation, can take a while.

Symbolic differentiation is ideal if your problem is simple enough. Symbolic methods are getting quite robust these days. SymPy is an excellent project for this that integrates well with NumPy. Look at the autowrap or lambdify functions or check out Jensen's blogpost about a similar question.

Automatic derivatives are very cool, aren't prone to numeric errors, but do require some additional libraries (google for this, there are a few good options). This is the most robust but also the most sophisticated/difficult to set up choice. If you're fine restricting yourself to numpy syntax then Theano might be a good choice.

Here is an example using SymPy

In [1]: from sympy import *
In [2]: import numpy as np
In [3]: x = Symbol('x')
In [4]: y = x**2 + 1
In [5]: yprime = y.diff(x)
In [6]: yprime
Out[6]: 2⋅x

In [7]: f = lambdify(x, yprime, 'numpy')
In [8]: f(np.ones(5))
Out[8]: [ 2.  2.  2.  2.  2.]
2 of 9
82

The most straight-forward way I can think of is using numpy's gradient function:

x = numpy.linspace(0,10,1000)
dx = x[1]-x[0]
y = x**2 + 1
dydx = numpy.gradient(y, dx)

This way, dydx will be computed using central differences and will have the same length as y, unlike numpy.diff, which uses forward differences and will return (n-1) size vector.

People also ask

Is there a calculator for derivatives?
Symbolab is the best derivative calculator, solving first derivatives, second derivatives, higher order derivatives, derivative at a point, partial derivatives, implicit derivatives, derivatives using definition, and more.
🌐
symbolab.com
symbolab.com › solutions › calculus calculator › derivative calculator
Derivative Calculator
What is the derivative of a Function?
The derivative of a function represents its a rate of change (or the slope at a point on the graph).
🌐
symbolab.com
symbolab.com › solutions › calculus calculator › derivative calculator
Derivative Calculator
How do you calculate derivatives?
To calculate derivatives start by identifying the different components (i.e. multipliers and divisors), derive each component separately, carefully set the rule formula, and simplify. If you are dealing with compound functions, use the chain rule.
🌐
symbolab.com
symbolab.com › solutions › calculus calculator › derivative calculator
Derivative Calculator
🌐
Mathway
mathway.com › Calculator › derivative-calculator
Derivative Calculator
The Derivative Calculator supports solving first, second...., fourth derivatives, as well as implicit differentiation and finding the zeros/roots. You can also get a better visual and understanding of the function by using our graphing tool.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-compute-derivative-using-numpy
How to compute derivative using Numpy? - GeeksforGeeks
July 23, 2025 - Here we are taking the expression ... function, f(x):\n", var) # calculating the derivative derivative = var.deriv() print("Derivative, f(x)'=", derivative) # calculates the derivative of after # given value of x print("When ...
🌐
Symbolab
symbolab.com › solutions › calculus calculator › derivative calculator
Derivative Calculator
Free derivative calculator - differentiate functions with all the steps. Type in any function derivative to get the solution, steps and graph
🌐
Wolfram|Alpha
wolframalpha.com › calculators › derivative-calculator
Derivative Calculator: Step-by-Step Solutions - Wolfram|Alpha
Free Derivative Calculator helps you solve first-order and higher-order derivatives. For trigonometric, logarithmic, exponential, polynomial expressions. Answers, graphs, alternate forms.
🌐
Medium
medium.com › @whyamit404 › understanding-derivatives-with-numpy-e54d65fcbc52
Understanding Derivatives with NumPy | by whyamit404 | Medium
February 8, 2025 - import numpy as np # Define the range for x from 0 to 10, split into 100 points x = np.linspace(0, 10, 100) # Define the function y = x^2 y = x**2 # Compute the derivative of y with respect to x using np.gradient dy_dx = np.gradient(y, x) # Print ...
Find elsewhere
🌐
Turing
turing.com › kb › derivative-functions-in-python
How to Calculate Derivative Functions in Python
Derivative calculations for different types of functions ... Below are a few code snippets that demonstrate the methods discussed earlier. The functions and input values in these examples can be adapted and modified to specific requirements. 1. Numerical differentiation using central difference · import numpy as np def f(x): return np.sin(x) def central_difference(f, x, h): return (f(x + h) - f(x - h)) / (2 * h) x = 0.5 h = 0.01 f_prime = central_difference(f, x, h) print(f_prime)
🌐
SciPy
docs.scipy.org › doc › scipy › reference › generated › scipy.differentiate.derivative.html
derivative — SciPy v1.17.0 Manual
This integrand is not compatible with derivative as written; for instance, the shape of the output will not be the same as the shape of x. Such a function could be converted to a compatible form with the introduction of additional parameters, but this would be inconvenient. In such cases, a simpler solution would be to use preserve_shape. >>> shapes = [] >>> def f(x): ... shapes.append(x.shape) ... x0, x1, x2, x3 = x ... return [x0, np.sin(3*x1), x2+np.sin(10*x2), np.sin(20*x3)*(x3-1)**2] >>> >>> x = np.zeros(4) >>> res = derivative(f, x, preserve_shape=True) >>> shapes [(4,), (4, 8), (4, 2), (4, 2), (4, 2), (4, 2)]
Top answer
1 of 2
7

The idea behind what you are trying to do is correct, but there are a couple of points to make it work as intended:

  1. There is a typo in calc_diffY(X), the derivative of X**2 is 2*X, not 2**X:
Copy  def calc_diffY(X):    
      yval_dash = 3*(X**2) + 2*X

By doing this you don't obtain much better results:

Copyyval_dash = [5, 16, 33, 56, 85]
numpyDiff = [10. 24. 44. 70.]
  1. To calculate the numerical derivative you should do a "Difference quotient" which is an approximation of a derivative
CopynumpyDiff = np.diff(yval)/np.diff(xval)

The approximation becomes better and better if the values of the points are more dense. The difference between your points on the x axis is 1, so you end up in this situation (in blue the analytical derivative, in red the numerical):

If you reduce the difference in your x points to 0.1, you get this, which is much better:

Just to add something to this, have a look at this image showing the effect of reducing the distance of the points on which the derivative is numerically calculated, taken from Wikipedia:

2 of 2
5

I like @lgsp's answer. I will add that you can directly estimate the derivative without having to worry about how much space there is between the values. This just uses the symmetric formula for calculating finite differences, described at this wikipedia page.

Take note, though, of the way delta is specified. I found that when it is too small, higher-order estimates fail. There's probably not a 100% generic value that will always work well!

Also, I simplified your code by taking advantage of numpy broadcasting over arrays to eliminate for loops.

Copyimport numpy as np

# selecte a polynomial equation
def f(x):
    y = x**3 + x**2 + 7
    return y

# manually differentiate the equation
def f_prime(x):
    return 3*x**2 + 2*x

# numerically estimate the first three derivatives
def d1(f, x, delta=1e-10):
    return (f(x + delta) - f(x - delta)) / (2 * delta)

def d2(f, x, delta=1e-5):
    return (d1(f, x + delta, delta) - d1(f, x - delta, delta)) / (2 * delta)

def d3(f, x, delta=1e-2):
    return (d2(f, x + delta, delta) - d2(f, x - delta, delta)) / (2 * delta)

# demo output
# note that functions operate in parallel on numpy arrays -- no for loops!
xval = np.array([1,2,3,4,5])

print('y  = ', f(xval))
print('y\' = ', f_prime(xval))
print('d1 = ', d1(f, xval))
print('d2 = ', d2(f, xval))
print('d3 = ', d3(f, xval))

And the outputs:

Copyy  =  [  9  19  43  87 157]
y' =  [ 5 16 33 56 85]
d1 =  [ 5.00000041 16.00000132 33.00002049 56.00000463 84.99995374]
d2 =  [ 8.0000051  14.00000116 20.00000165 25.99996662 32.00000265]
d3 =  [6.         6.         6.         6.         5.99999999]
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.polyder.html
numpy.polyder — NumPy v2.2 Manual
The derivative of the polynomial \(x^3 + x^2 + x^1 + 1\) is: >>> import numpy as np · >>> p = np.poly1d([1,1,1,1]) >>> p2 = np.polyder(p) >>> p2 poly1d([3, 2, 1]) which evaluates to: >>> p2(2.) 17.0 · We can verify this, approximating the derivative with (f(x + h) - f(x))/h: >>> (p(2.
🌐
eMathHelp
emathhelp.net › calculators › calculus-1 › derivative-calculator
Derivative Calculator - eMathHelp
The online calculator will calculate the derivative of any function using the common rules of differentiation (product rule, quotient rule, chain rule, etc.), with steps shown. It can handle polynomial, rational, irrational, exponential, logarithmic, trigonometric, inverse trigonometric, hyperbolic, and inverse hyperbolic functions.
🌐
MathPortal
mathportal.org › calculators › calculus › derivative-calculator.php
Derivative Calculator
This calculator computes the first, second, and third derivatives of a given function. You can also evaluate the derivative at a given point. It uses product quotient and chain rule to find the derivative.
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.gradient.html
numpy.gradient — NumPy v2.5.dev0 Manual
With a similar procedure the forward/backward approximations used for boundaries can be derived. ... Quarteroni A., Sacco R., Saleri F. (2007) Numerical Mathematics (Texts in Applied Mathematics). New York: Springer. ... Durran D. R. (1999) Numerical Methods for Wave Equations in Geophysical Fluid Dynamics. New York: Springer. ... Fornberg B. (1988) Generation of Finite Difference Formulas on Arbitrarily Spaced Grids, Mathematics of Computation 51, no. 184 : 699-706. PDF. ... Try it in your browser! >>> import numpy as np >>> f = np.array([1, 2, 4, 7, 11, 16]) >>> np.gradient(f) array([1.
🌐
App Store
apps.apple.com › np › app › derivative-calculator-solver › id1593820522
‎Derivative Calculator Solver on the App Store
November 5, 2021 - Derivative Calculator gives step-by-step help on finding derivatives. Derivative function calculator to solve your derivation equations. Use this limit derivative calculator app to calculate derivative of a function perfectly.
🌐
BYJUS
byjus.com › derivative-calculator
How to Use the Derivative Calculator?
December 13, 2022 - BYJU’S online derivative calculator or differentiation calculator tool makes the calculations faster, and it shows the first, second, third-order derivatives of the function in a fraction of seconds.
🌐
AllMath
allmath.com › derivative.php
Derivative Calculator - Differentiation calculator
Derivative calculator finds the derivative of a function with respect to a variable. Our differentiation calculator shows the step-by-step calculation.