合并多个浮点数组并计算每个项的平均值

本文关键字:计算 平均值 数组 合并 | 更新日期: 2023-09-27 17:59:08

我有多个浮点数组。他们的长度必须不匹配。现在,我必须将所有这些交易到一个单独的浮点数组中。为了推销它们,我想计算每个指数的平均值。这意味着:

output[n] = (input0[n] + input1[n] + input2[n] ... + inputx[n]) / x

所有这些都必须计算得非常快。我不在乎代码是易读还是可扩展。它只需要尽可能快:

我创建了以下代码:

private void Mix()
{
    List<float[]> input = new List<float[]>();
    //...
    //input has [n] float arrays.
    //eg:
    //0: [0.5, 0.3, 0.6, 0.1, -0.3, 0.1, -0.9]
    //1: [0.1, 0.7, -0.2, 0.8, -0.2]
    //2: [-0.3, 0.9, 0.5, 0.4, 0.8, -0.6]
    //3: [0.5, -0.2, 0.4]
    //-----------------------------------------------
    //the average value for the first value would have to be this:
    //(0.5 + 0.1 - 0.3 + 0.5) / 4
    //mix all together:
    //===================

    //create an output buffer
    int length = input.Max(x => x.Length);
    float[] output = new float[length];
    for (int n = 0; n < length; n++)
    {
        float value = 0;
        int count = 0;
        for (int x = 0; x < input.Count; x++)
        {
            float[] inputBuffer = input[x]; //select the input array
            if (inputBuffer.Length >= n) //check whether there is a value to get
            {
                value += inputBuffer[n]; //get the value of the input array
                count++;
            }
        }
        output[n] = value / count; //calculate the average
    }
}

正如您所看到的,它包含嵌套的for循环。我想,这个代码到目前为止还不够快。那么有什么方法可以让它更快吗?

合并多个浮点数组并计算每个项的平均值

有两件事让它更快:

  1. 重新排列代码,使if语句位于外循环而不是内循环中。考虑"提前退出",而不是"验证每个指数是否在范围内"。

  2. 在此处利用SIMD库:http://blogs.msdn.com/b/dotnet/archive/2014/04/07/the-jit-finally-proposed-jit-and-simd-are-getting-married.aspx

您可以尝试使用专用库添加向量,例如,请参阅推荐C#矩阵库以获取候选列表。正如Scott已经指出的,这不会改变问题的基本运行时复杂性,但它可能会运行得更快,并针对此类操作进行了优化。