插值一个给定的数组以达到新的长度

问题描述

为了插值2个值,我可以使用

lerp(int a,int b) {
   return (a + b) / 2;
}

现在假设我有一个数组(1、30、100、300),我想将其插值为大小为N的数组(例如N = 10)。

如果N == 7,则:

1,15,30,65,100,200,300

我不知道如何将4个值插值为10。我需要一个看起来像这样的方法:

interpolate(fina int[] input,final int newSize) {
    int[] res = new int[newSize];
    ...
    return res;
}

即使在我上面的示例中,newSize为7、10或任何其他值,也可以使用。

有什么想法要实现吗?

解决方法

已解决。

public static double[] interpolate(double[] x,int newLength) {
    double[] y = null;
    if (newLength > 0) {
        int N = x.length;
        if (N == 1) {
            y = new double[1];
            y[0] = x[0];
            return y;
        } else if (newLength == 1) {
            y = new double[1];
            int ind = (int) Math.floor(N * 0.5 + 0.5);
            ind = Math.max(1,ind);
            ind = Math.min(ind,N);
            y[0] = x[ind - 1];
            return y;
        } else {
            y = new double[newLength];
            double Beta = ((double) newLength) / N;
            double newBeta = 1.0;

            if (newLength > 2)
                newBeta = (N - 2.0) / (newLength - 2.0);

            y[0] = x[0];
            y[1] = x[1];
            y[newLength - 1] = x[N - 1];

            double tmp,alpha;
            int i,j;
            for (i = 2; i <= newLength - 2; i++) {
                tmp = 1.0 + (i - 1) * newBeta;
                j = (int) Math.floor(tmp);
                alpha = tmp - j;
                y[i] = (1.0 - alpha) * x[Math.max(0,j)] + alpha * x[Math.min(N - 1,j + 1)];
            }
        }
    }

    return y;
}

/**
 * Find the maximum of all elements in the array,ignoring elements that are NaN.
 * @param data
 * @return
 */
public static double max(double[] data) {
    double max = Double.NaN;
    for (int i = 0; i < data.length; i++) {
        if (Double.isNaN(data[i]))
            continue;
        if (Double.isNaN(max) || data[i] > max)
            max = data[i];
    }
    return max;
}

public static int max(int[] data) {
    int max = data[0];
    for (int i = 1; i < data.length; i++) {
        if (data[i] > max)
            max = data[i];
    }
    return max;
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...