How to resolve the algorithm Averages/Simple moving average step by step in the V (Vlang) programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Averages/Simple moving average step by step in the V (Vlang) 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 V (Vlang) programming language

Source code in the v programming language

fn sma(period int) fn(f64) f64 {
    mut i := int(0)
    mut sum := f64(0)
    mut storage := []f64{len: 0, cap:period}
 
    return fn[mut storage, mut sum, mut i, period](input f64) f64 {
        if storage.len < period {
            sum += input
            storage << input
        }
 
        sum += input - storage[i]
        storage[i], i = input, (i+1)%period
        return sum / f64(storage.len)
    }
}
 
fn main() {
    sma3 := sma(3)
    sma5 := sma(5)
    println("x       sma3   sma5")
    for x in [f64(1), 2, 3, 4, 5, 5, 4, 3, 2, 1] {
        println("${x:5.3f}  ${sma3(x):5.3f}  ${sma5(x):5.3f}")
    }
}

  

You may also check:How to resolve the algorithm Mayan numerals step by step in the Phix programming language
You may also check:How to resolve the algorithm Sorting algorithms/Pancake sort step by step in the D programming language
You may also check:How to resolve the algorithm Empty program step by step in the Elena programming language
You may also check:How to resolve the algorithm Even or odd step by step in the Action! programming language
You may also check:How to resolve the algorithm Bulls and cows step by step in the PHP programming language