Computing a moving average

Below is a Python Mode example that uses random numbers as data. You can adapt it for Java Mode, and step through an array of data instead, or use some other source, as needed.

The strategy for timing used here is to set a frameRate of 2 frames per second, and test the divisibility of frameCount by some modulus. If the result is 0, get a new value and display the average for one frame (0.5 seconds). During all other frames, display that new value instead of the average. You can change the modulus to change the timing.

# use random integers as data
old, new = floor(random(0, 101)), floor(random(0, 101))
def setup():
    size(240, 100)
    frameRate(2) # 2 frames per second; each frame displays for 0.5 seconds
    textSize(48)
    textAlign(LEFT, CENTER)
    fill(0)
    
def draw():
    global old, new
    background(255)
    if frameCount % 6 == 0: # can change modulus to adjust time of display of new value
        # get new value; display average of old and new values for one frame (0.5 seconds)
        old, new = new, floor(random(0, 101)) # use random integers as data
        text(float(old + new) / 2, 10, height / 2)
    else:
        # display new value whenever frameCount not evenly divisible by modulus
        text(float(new), 10, height / 2)

EDIT (March 30, 2021):

The above assumes that you consider frameCount to be a reliable measure of time. If not, you will obviously need to use another strategy.

The above also has new values becoming available at regular intervals. If, instead, they arrive at unpredictable times, you can maintain a rate of 60 frames per second. Whenever a new value arrives, save the frame number, let’s say, in a variable named eventFrameCount, and get the old and new values into the appropriate variables. During each frame, display the prescribed average if frameCount - eventFrameCount <= 30. Thereafter, display the most recent value during each frame until the next value arrives.

1 Like