c ++中的np.gradient替代项

问题描述 投票:0回答:2

我需要编写一个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. ])

有人知道如何实现吗?

python c++ numpy gradient
2个回答
0
投票

我自己实现了一个非常简单的功能,因为这个问题太容易了...


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;
}

0
投票

根据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

© www.soinside.com 2019 - 2024. All rights reserved.