How to resolve the algorithm Averages/Simple moving average step by step in the Forth programming language
How to resolve the algorithm Averages/Simple moving average step by step in the Forth 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 Forth programming language
Source code in the forth programming language
: f+! ( f addr -- ) dup f@ f+ f! ;
: ,f0s ( n -- ) falign 0 do 0e f, loop ;
: period @ ;
: used cell+ ;
: head 2 cells + ;
: sum 3 cells + faligned ;
: ring ( addr -- faddr )
dup sum float+ swap head @ floats + ;
: update ( fvalue addr -- addr )
dup ring f@ fnegate dup sum f+!
fdup dup ring f! dup sum f+!
dup head @ 1+ over period mod over head ! ;
: moving-average
create ( period -- ) dup , 0 , 0 , 1+ ,f0s
does> ( fvalue -- avg )
update
dup used @ over period < if 1 over used +! then
dup sum f@ used @ 0 d>f f/ ;
3 moving-average sma
1e sma f. \ 1.
2e sma f. \ 1.5
3e sma f. \ 2.
4e sma f. \ 3.
You may also check:How to resolve the algorithm Unbias a random generator step by step in the ERRE programming language
You may also check:How to resolve the algorithm Rep-string step by step in the Action! programming language
You may also check:How to resolve the algorithm Find limit of recursion step by step in the TSE SAL programming language
You may also check:How to resolve the algorithm Enforced immutability step by step in the Rust programming language
You may also check:How to resolve the algorithm Read a configuration file step by step in the Ada programming language