numpy.gradient 间距不均匀

non-uniform spacing with numpy.gradient

我不确定在使用 numpy.gradient 时如何指定非均匀间距。

这是 y = x**2 的一些示例代码。

import numpy as np
import matplotlib.pyplot as plt

x = [0.0, 2.0, 4.0, 8.0, 16.0]
y = [0.0, 4.0, 16.0, 64.0, 256.0]
dydx = [0.0, 4.0, 8.0, 16.0, 32.0] # analytical solution

spacing = [0.0, 2.0, 2.0, 4.0, 8.0] #added a zero at the start to get length matching up with y

m = np.gradient(y, spacing)

plt.plot(x, y, 'bo',
         x, dydx, 'r-', #analytical solution
         x, m, 'ro')    #calculated solution
plt.show()

间距数组的长度总是比我要计算梯度的数组少一。添加一个零以使长度匹配(如上面的示例代码中所示)会给出错误的答案,其中一个点具有无限梯度。

我无法理解/无法遵循 numpy.gradient 非均匀间距文档 (https://docs.scipy.org/doc/numpy/reference/generated/numpy.gradient.html)

我应该如何指定点之间的间距?有其他方法吗?

Numpy 版本 1.9.2

函数的API比较混乱。对于非均匀间隔的样本点,gradient function 采用点的 坐标 而不是间距:

varargs : list of scalar or array, optional

Spacing between f values. Default unitary spacing for all dimensions. Spacing can be specified using:

  1. single scalar to specify a sample distance for all dimensions.
  2. N scalars to specify a constant sample distance for each dimension. i.e. dx, dy, dz, …
  3. N arrays to specify the coordinates of the values along each dimension of F. The length of the array must match the size of the corresponding dimension
  4. Any combination of N scalars/arrays with the meaning of 2. and 3.

我稍微修改了你的例子:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(10)
x.sort()
y = x**2
dydx = 2*x

dydx_grad = np.gradient(y, x)

plt.plot(x, dydx, 'k-', label='analytical solution')
plt.plot(x, dydx_grad, 'ro', label='calculated solution')
plt.legend(); plt.xlabel('x'); plt.ylabel('dy / dx'); plt.show();