How to resolve the algorithm Averages/Simple moving average step by step in the Groovy programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Averages/Simple moving average step by step in the Groovy programming language

Table of Contents

Problem Statement

Computing the simple moving average of a series of numbers. Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. A simple moving average is a method for computing an average of a stream of numbers by only averaging the last   P   numbers from the stream,   where   P   is known as the period. It can be implemented by calling an initialing routine with   P   as its argument,   I(P),   which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last   P   of them, lets call this   SMA(). The word   stateful   in the task description refers to the need for   SMA()   to remember certain information between calls to it:

Stateful   also means that successive calls to   I(),   the initializer,   should return separate routines that do   not   share saved state so they could be used on two independent streams of data. Pseudo-code for an implementation of   SMA   is:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Averages/Simple moving average step by step in the Groovy programming language

Source code in the groovy programming language

def simple_moving_average = { size ->
    def nums = []
    double total = 0.0
    return { newElement ->
        nums += newElement
        oldestElement = nums.size() > size ? nums.remove(0) : 0
        total += newElement - oldestElement
        total / nums.size()
    }
}

ma5 = simple_moving_average(5)

(1..5).each{ printf( "%1.1f ", ma5(it)) }
(5..1).each{ printf( "%1.1f ", ma5(it)) }


  

You may also check:How to resolve the algorithm Binary search step by step in the jq programming language
You may also check:How to resolve the algorithm Amicable pairs step by step in the 8086 Assembly programming language
You may also check:How to resolve the algorithm Tau number step by step in the Java programming language
You may also check:How to resolve the algorithm Sieve of Eratosthenes step by step in the Cowgol programming language
You may also check:How to resolve the algorithm Longest increasing subsequence step by step in the Tcl programming language