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

Published on 12 May 2024 09:40 PM

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

Source code in the nim programming language

import deques

proc simplemovingaverage(period: int): auto =
  assert period > 0

  var
    summ, n = 0.0
    values: Deque[float]
  for i in 1..period:
    values.addLast(0)

  proc sma(x: float): float =
    values.addLast(x)
    summ += x - values.popFirst()
    n = min(n+1, float(period))
    result = summ / n

  return sma

var sma = simplemovingaverage(3)
for i in 1..5: echo sma(float(i))
for i in countdown(5,1): echo sma(float(i))

echo ""

var sma2 = simplemovingaverage(5)
for i in 1..5: echo sma2(float(i))
for i in countdown(5,1): echo sma2(float(i))


  

You may also check:How to resolve the algorithm Machine code step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Multiple distinct objects step by step in the 11l programming language
You may also check:How to resolve the algorithm Filter step by step in the Ol programming language
You may also check:How to resolve the algorithm Arithmetic-geometric mean/Calculate Pi step by step in the Scala programming language
You may also check:How to resolve the algorithm Nautical bell step by step in the Python programming language