File-By-File
RollingAverage

RollingAverage

A rolling average/moving average is a type of average that takes the average of a predetermined amount of previous numbers. Every time a new number is added to that average, the oldest number in the rolling average (whatever number has an index of size - 1) will be removed from the array, all the other numbers will be shifted over by 1, and the array's 0th number will be the new number.

This class uses System.arraycopy() to efficiently manage the underlying array of primitive double values for performance.

Methods

RollingAverage(int size)

Constructs a new RollingAverage with a specified size. The size determines how many previous numbers are included in the average. A larger size results in a more smoothed average but is more computationally intensive.

average()

Calculates and returns the current rolling average. If the data has not changed since the last calculation, it returns the previously computed average. Otherwise, it re-calculates the sum of the stored numbers and divides by the number of elements currently in the average.

rotate(double newValue)

Private helper method. Shifts all existing elements in the internal data array one position to the right (towards higher indices) and inserts newValue at index 0 (the front of the queue). The last element is effectively removed.

add(double value)

Adds a new value to the rolling average. This method calls rotate() to update the internal data array and then forces a recalculation of the average. Returns the newly calculated average.