The key phrase from the docs is:

The gradient is computed using second order accurate central differences in the interior points ...

This means that each group of three contiguous points is adjusted to a parabola (2nd order polynomial) and its slope at the location of the central point is used as the gradient.

For evenly spaced data (with a spacing of 1) the formula is very simple:

g(i) = 0.5 f(i+1) - 0.5 f(i-1)

Then comes the problematic part:

... and either first or second order accurate one-sides (forward or backwards) differences at the boundaries.

There is neither f(i+1) at the right boundary nor f(i-1) at the left boundary.

So you can use a simple 1st order approximation

g(0) = f(1) - f(0)
g(n) = f(n) - f(n-1)

or a more complex 2nd order approximation

g(0) = -1.5 f(0) + 2 f(1) - 0.5 f(2)
g(n) = 0.5 f(n-2) - 2 f(n-1) + 1.5 f(n)

The effect can be seen in this example, copied from the docs:

>>> x = np.array([0, 1, 2, 3, 4])
>>> f = x**2
>>> np.gradient(f, edge_order=1)
array([1., 2., 4., 6., 7.])
>>> np.gradient(f, edge_order=2)
array([0., 2., 4., 6., 8.])

The derivation of the coefficient values can be found here.

Answer from aerobiomat on Stack Overflow
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.gradient.html
numpy.gradient — NumPy v2.1 Manual
>>> x = np.array([0, 1, 2, 3, 4]) >>> f = x**2 >>> np.gradient(f, edge_order=1) array([1., 2., 4., 6., 7.]) >>> np.gradient(f, edge_order=2) array([0., 2., 4., 6., 8.])
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.gradient.html
numpy.gradient — NumPy v2.4 Manual
>>> x = np.array([0, 1, 2, 3, 4]) >>> f = x**2 >>> np.gradient(f, edge_order=1) array([1., 2., 4., 6., 7.]) >>> np.gradient(f, edge_order=2) array([0., 2., 4., 6., 8.])
Discussions

DOC: suggestion, beware of `np.gradient( edge_order=2 )`
For example, say you bike up a steep hill, then almost flat, slope a degrees then 1 degree. What's the slope at the edge ? Extrapolating a -> 1 -> 1 + (1 - a) / 2 goes negative for a > 2. """ ... """ show how np.gradient( edge_order=2 ) can overshoot: slopes 10, 1 -> -3.5 """ import numpy as np ... More on github.com
🌐 github.com
6
January 16, 2025
python - Second order gradient in numpy - Stack Overflow
edge_order : {1, 2}, optional Gradient is calculated using Nth order accurate differences at the boundaries. Default: 1. New in version 1.9.1. Returns: gradient : ndarray N arrays of the same shape as f giving the derivative of f with respect to each dimension. ... My solution is to create a function similar to np.gradient that calculates the 2nd derivatives numerically from the array data. import numpy ... More on stackoverflow.com
🌐 stackoverflow.com
What is the purpose of np.gradient() edge_order?
Well, the documentation says: edge_order{1, 2}, optional Gradient is calculated using N-th order accurate differences at the boundaries. Default: 1. Heck if I know what all that means though. https://numpy.org/doc/stable/reference/generated/numpy.gradient.html More on reddit.com
🌐 r/learnpython
2
0
January 8, 2023
Increasing the precision of np.gradient?
np.gradient takes an array-like in the first argument, i.e., you provide the function values, and it returns the gradient at the same points. That's really all it can do because it doesn't know the function itself. MATLAB's gradient takes a function, so you can give it any precision you like, and it'll sample that function as necessary. So I think the answer is you just need to sample the function yourself at your desired step size, then pass the result to np.gradient. More on reddit.com
🌐 r/learnpython
3
7
January 7, 2023
🌐
NumPy
numpy.org › doc › 1.25 › reference › generated › numpy.gradient.html
numpy.gradient — NumPy v1.25 Manual
>>> x = np.array([0, 1, 2, 3, 4]) >>> f = x**2 >>> np.gradient(f, edge_order=1) array([1., 2., 4., 6., 7.]) >>> np.gradient(f, edge_order=2) array([0., 2., 4., 6., 8.])
🌐
SciPy
docs.scipy.org › doc › numpy-1.9.3 › reference › generated › numpy.gradient.html
numpy.gradient — NumPy v1.9 Manual
>>> x = np.array([0, 1, 2, 3, 4]) >>> dx = np.gradient(x) >>> y = x**2 >>> np.gradient(y, dx, edge_order=2) array([-0., 2., 4., 6., 8.]) numpy.ediff1d · numpy.cross · © Copyright 2008-2009, The Scipy community. Last updated on Oct 18, 2015.
🌐
GitHub
github.com › numpy › numpy › issues › 28166
DOC: suggestion, beware of `np.gradient( edge_order=2 )` · Issue #28166 · numpy/numpy
January 16, 2025 - For example, say you bike up a steep hill, then almost flat, slope a degrees then 1 degree. What's the slope at the edge ? Extrapolating a -> 1 -> 1 + (1 - a) / 2 goes negative for a > 2. """ ... """ show how np.gradient( edge_order=2 ) can ...
Author   denis-bz
🌐
NumPy
numpy.org › doc › 2.0 › reference › generated › numpy.gradient.html
numpy.gradient — NumPy v2.0 Manual
>>> x = np.array([0, 1, 2, 3, 4]) >>> f = x**2 >>> np.gradient(f, edge_order=1) array([1., 2., 4., 6., 7.]) >>> np.gradient(f, edge_order=2) array([0., 2., 4., 6., 8.])
Find elsewhere
Top answer
1 of 6
8

I'll second @jrennie's first sentence - it can all depend. The numpy.gradient function requires that the data be evenly spaced (although allows for different distances in each direction if multi-dimensional). If your data does not adhere to this, than numpy.gradient isn't going to be much use. Experimental data may have (OK, will have) noise on it, in addition to not necessarily being all evenly spaced. In this case it might be better to use one of the scipy.interpolate spline functions (or objects). These can take unevenly spaced data, allow for smoothing, and can return derivatives up to k-1 where k is the order of the spline fit requested. The default value for k is 3, so a second derivative is just fine. Example:

spl = scipy.interpolate.splrep(x,y,k=3) # no smoothing, 3rd order spline
ddy = scipy.interpolate.splev(x,spl,der=2) # use those knots to get second derivative 

The object oriented splines like scipy.interpolate.UnivariateSpline have methods for the derivatives. Note that the derivative methods are implemented in Scipy 0.13 and are not present in 0.12.

Note that, as pointed out by @JosephCottham in comments in 2018, this answer (good for Numpy 1.08 at least), is no longer applicable since (at least) Numpy 1.14. Check your version number and the available options for the call.

2 of 6
6

There's no universal right answer for numerical gradient calculation. Before you can calculate the gradient about sample data, you have to make some assumption about the underlying function that generated that data. You can technically use np.diff for gradient calculation. Using np.gradient is a reasonable approach. I don't see anything fundamentally wrong with what you are doing---it's one particular approximation of the 2nd derivative of a 1-D function.

🌐
SciPy
docs.scipy.org › doc › numpy-1.10.1 › reference › generated › numpy.gradient.html
numpy.gradient — NumPy v1.10 Manual
For two dimensional arrays, the return will be two arrays ordered by axis. In this example the first array stands for the gradient in rows and the second one in columns direction: >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=np.float)) [array([[ 2., 2., -1.], [ 2., 2., -1.]]), array([[ 1. , 2.5, 4. ], [ 1. , 1. , 1. ]])] >>> x = np.array([0, 1, 2, 3, 4]) >>> dx = np.gradient(x) >>> y = x**2 >>> np.gradient(y, dx, edge_order=2) array([-0., 2., 4., 6., 8.])
🌐
NumPy
numpy.org › doc › 2.3 › reference › generated › numpy.gradient.html
numpy.gradient — NumPy v2.3 Manual
>>> x = np.array([0, 1, 2, 3, 4]) >>> f = x**2 >>> np.gradient(f, edge_order=1) array([1., 2., 4., 6., 7.]) >>> np.gradient(f, edge_order=2) array([0., 2., 4., 6., 8.])
🌐
Finxter
blog.finxter.com › home › learn python blog › np.gradient() — a simple illustrated guide
np.gradient() - A Simple Illustrated Guide - Be on the Right Side of Change
June 24, 2022 - Just to refresh your memory, here is the argument table of numpy.gradient(): We can set the argument edge_order to be 1 or 2. Its default value is 1. First, our previous basic example uses its default value, 1.
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.gradient.html
numpy.gradient — NumPy v2.5.dev0 Manual
>>> x = np.array([0, 1, 2, 3, 4]) >>> f = x**2 >>> np.gradient(f, edge_order=1) array([1., 2., 4., 6., 7.]) >>> np.gradient(f, edge_order=2) array([0., 2., 4., 6., 8.])
🌐
Finxter
blog.finxter.com › 5-best-ways-to-return-the-gradient-of-an-n-dimensional-array-and-specify-edge-order-in-python
5 Best Ways to Return the Gradient of an N Dimensional Array and Specify Edge Order in Python – Be on the Right Side of Change
The first array is the gradient along the vertical axis (rows), and the second is along the horizontal axis (columns). Python’s NumPy library allows customization of the edge order in the gradient computation, offering the ability to choose a higher-order approximation on the boundaries.
🌐
Educative
educative.io › answers › how-to-use-the-numpygradient-function-for-a-2d-array-in-python
How to use the numpy.gradient function for a 2D array in Python
For gradient approximation, the ... two-dimensional (2D) array in Python, we can use a list of lists. numpy.gradient(f, *varargs, axis=None, edge_order=1)...
🌐
SciPy
docs.scipy.org › doc › numpy-1.15.0 › reference › generated › numpy.gradient.html
numpy.gradient — NumPy v1.15 Manual
>>> x = np.array([0, 1, 2, 3, 4]) >>> f = x**2 >>> np.gradient(f, edge_order=1) array([ 1., 2., 4., 6., 7.]) >>> np.gradient(f, edge_order=2) array([-0., 2., 4., 6., 8.]) The axis keyword can be used to specify a subset of axes of which the gradient is calculated · >>> np.gradient(np.array([[1, ...
🌐
MindSpore
mindspore.cn › docs › en › r1.7 › api_python › numpy › mindspore.numpy.gradient.html
mindspore.numpy.gradient | MindSpore 1.7 documentation | MindSpore
ValueError – If axis values out ... Platforms: Ascend GPU CPU · Examples · >>> import mindspore.numpy as np >>> output = np.gradient([[1, 2, 6], [3, 4, 5]], axis=-1) >>> print(output) [[1....
🌐
Skytowner
skytowner.com › explore › numpy_gradient_method
NumPy | gradient method with Examples
Allowed values are 1 and 2. By default, edge_order=2. ... The axis along which to compute the gradient. A Numpy array holding the gradients of the data points.
🌐
MindSpore
mindspore.cn › docs › en › r2.0 › api_python › numpy › mindspore.numpy.gradient.html
mindspore.numpy.gradient | MindSpore 2.0 documentation | MindSpore
ValueError – If axis values out ... Platforms: Ascend GPU CPU · Examples · >>> import mindspore.numpy as np >>> output = np.gradient([[1, 2, 6], [3, 4, 5]], axis=-1) >>> print(output) [[1....