移动平均/总算法

Pet*_*217 2 java algorithm moving-average

我需要在平面文件读取循环中跟踪最近7天的工作时间.它被用来衡量工作名单的"疲劳性".

现在我有一些有用的东西,但它似乎相当冗长,我不确定是否有一种更简洁的模式.

目前,我有一个带有静态数组的Java类来保存最后x天的数据,然后当我读完文件时,我切掉第一个元素并将另外6个元素(一周滚动总数)移回一个.该静态数组的处理以其自己的方法完成,即.

/**
 * Generic rolling average/total method. Keeps adding to an array of 
 * last 'x' seen.
 * @param d Datum point you want to add/track.
 * @param i Number of rolling periods to keep track of eg. 7 = last 7 days
 *          NOT USED AT MOMENT DURING TESTING
 * @param initFlag A flag to initialize static data set back to empty.
 * @return The rolling total for i periods.
 */
private double rollingTotal(double d, boolean initFlag) {
    // Initialize running total array eg. for new Employyes
    if (initFlag) {
        runningTotal = null;
    }
    else {
        // move d+1 back to d eg. element 6 becomes element 5
        for (int x = 0; x< 6 ; x++) {
            runningTotal[x] = runningTotal[x+1];
        }
        // Put current datum point at end of array.
        runningTotal[6]= d;
    }
    // Always return sum of array when this method is called.
    double myTotal = 0.0;
    for (int x = 0; x<7; x++) {
        myTotal+= runningTotal[x];
    }
    System.err.print(Arrays.toString(runningTotal)+ '\n' );
    return myTotal;
}
Run Code Online (Sandbox Code Playgroud)

我的问题:这是一种合理的设计方法,还是有一些令人眼花缭乱的明显和简单的任务?多谢你们

Jim*_*hel 5

这当然有效,但你做的工作比你要多一些.您可以避免移动所有数据,并且可以对其进行设置,以便计算下一个总数是减去最旧值并添加新值.

例如:

// assume that currentIndex is where you want to add the new item
// You have another value, currentTotal, that is initialized at 0.
currentTotal = currentTotal - runningTotal[currentIndex] + d;
runningTotal[currentIndex] = d;
// increment the index.
currentIndex = (currentIndex + 1) % 7;
Run Code Online (Sandbox Code Playgroud)

这使用循环缓冲区并保持currentTotal它始终可用.