Higher order central differences using NumPy.gradient()

Hello everyone,

I am new to Python and am still learning it. So my apologies if this is a basic question.

I am given two arrays: X and Y. Where Y=2*(x^2)+x/2. I need to calculate the first and the fifth order central differences of Y with respect to X using the numpy.gradient function.

For the first order central difference, I used np.gradient(Y,X) and it works perfectly fine.

I am not sure how to calculate the fifth order central difference. I went to the NumPy.gradient reference, but that didn’t help. Is it possible to calculate the higher order central differences using the gradient function? If yes, what should be the syntax?

Any help or suggestion would be greatly appreciated!

Thank you.

I’m not sure if I have understood your question, but I think you are asking to compute the first and fifth derivatives. If so, you can do this:

dydx = np.gradient(y, x)  # First derivative.
d2ydx2 = np.gradient(dydx, x)  # Second derivative.
d3ydx3 = np.gradient(d2ydx2, x)  # Third derivative.
d4ydx4 = np.gradient(d3ydx3, x)  # Fourth derivative.
d5ydx5 = np.gradient(d4ydx4, x)  # Fifth derivative.

But keep in mind that np.gradient is only a numerical approximation, so it will introduce some error. Each time you call it, the errors will compound. I would be very surprised if the fifth derivative was as accurate as the first.

Your Y is a quadratic equation. So the we can use calculus to compute the exact derivatives, and check the accuracy of the computed points.

Does this help?


Hi @steven.daprano ,

Thanks. That helps. Really appreciate your help.

Hi @steven.daprano ,

I have a related question.

If I want to calculate the first derivative using a five-point stencil (Five-point stencil - Wikipedia), does the gradient function have a special argument that needs to be passed?

numpy.gradient doesn’t have an option for that.

Perhaps another numpy function, or a scipy function, may help you.

@steven.daprano ,

Thanks for the suggestion. But in numpy or the scipy manual, I don’t see any other functions that does what I need.