我需要编写一个C ++函数来计算数组的梯度,例如numpy中的np.gradient
函数:
>>> f = np.array([1, 2, 4, 7, 11, 16], dtype=float)
>>> np.gradient(f)
array([1. , 1.5, 2.5, 3.5, 4.5, 5. ])
有人知道如何实现吗?
我自己实现了一个非常简单的功能,因为这个问题太容易了...
vector<double> gradient(vector<double> input){
if (input.size() <= 1) return input;
vector<double> res;
for(int j=0; j<input.size(); j++) {
int j_left = j - 1;
int j_right = j + 1;
if (j_left < 0) {
j_left = 0; // use your own boundary handler
j_right = 1;
}
if (j_right >= input.size()){
j_right = input.size() - 1;
j_left = j_right - 1;
}
// gradient value at position j
double dist_grad = (input[j_right] - input[j_left]) / 2.0;
res.push_back(dist_grad);
}
return res;
}
根据https://docs.scipy.org/doc/numpy/reference/generated/numpy.gradient.html中的文档
f'[x] =(f [x + 1]-f [x-1])/ 2.0 * h + o(h ^ 2)
因此您可以将元素从1
移至n-1
并计算(f[i+1] - f[i-1]) / 2.0