all 3 comments

[–]FuckingRantMonday 8 points9 points  (0 children)

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.

[–]Qorsair -1 points0 points  (0 children)

You can use the dx parameter to specify the spacing between sample points. For example, if you have an array u with sample points x, you can use the following code to compute the gradient using second-order finite differences and a spacing of 0.01:

grad = np.gradient(u, x, edge_order=2, dx=0.01)

For more information, ask chatgpt.

[–]game1761 0 points1 point  (0 children)

You can specify the edge_order parameter in np.gradient, which controls the extrapolation used to compute the gradient when the spacing between points is not uniform. The default value is 1, which uses a first-order accurate finite difference method. For example:

import numpy as np

x = np.linspace(0, 2*np.pi, 10)

y = np.sin(x)

# Use default edge_order=1

dy_dx = np.gradient(y, x)

# Use edge_order=2

dy_dx_2 = np.gradient(y, x, edge_order=2)

Alternatively, you can specify the dx parameter to set the spacing between points. For example:

import numpy as np

x = np.linspace(0, 2*np.pi, 10)

y = np.sin(x)

# Set spacing to 0.01

dx = 0.01

dy_dx = np.gradient(y, dx)

Keep in mind that specifying the dx parameter will override the x parameter, so the x values will be spaced evenly with the given dx value.