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

Published on 7 June 2024 03:52 AM
#C

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

The provided C code implements a simple sliding window moving average (SMA) library. Let's break down the code step by step:

  1. Header Includes:

    #include <stdio.h>
    #include <stdlib.h>
    #include <stdarg.h>

    These headers include standard input/output functions, dynamic memory allocation functions, and support for variable argument lists (stdarg.h).

  2. Custom Types and Structs:

    • sma_obj_t: This struct represents an SMA object. It contains the following fields:

      • sma: The current SMA value.
      • sum: The sum of the values in the sliding window.
      • period: The period of the SMA (i.e., the number of values in the sliding window).
      • values: An array to store the values in the sliding window.
      • lv: The current level (index) in the values array.
    • sma_result_t: This union represents the result of an SMA operation. It can either contain a pointer to an SMA object (handle), the current SMA value (sma), or an array of values (values).

  3. sma() Function:

    This function is the core of the SMA library. It takes an enum Action and a variable number of arguments (...) to perform various operations on SMA objects.

    • SMA_NEW: Creates a new SMA object with the specified period and returns a pointer to it.

    • SMA_FREE: Frees the memory allocated for an SMA object.

    • SMA_VALUES: Returns the values array of an SMA object.

    • SMA_MEAN: Returns the current sma value of an SMA object.

    • SMA_ADD: Adds a new value to an SMA object and updates the SMA calculation.

  4. Main Function:

    int main()
    {
     int i;
    
     sma_obj_t *h3 = sma(SMA_NEW, 3).handle;
     sma_obj_t *h5 = sma(SMA_NEW, 5).handle;
    
     for(i=0; i < sizeof(v)/sizeof(double) ; i++) {
       printf("next number %lf, SMA_3 = %lf, SMA_5 = %lf\n",
              v[i], sma(SMA_ADD, h3, v[i]).sma, sma(SMA_ADD, h5, v[i]).sma);
     }
    
     sma(SMA_FREE, h3);
     sma(SMA_FREE, h5);
     return 0;
    }
    • This is the entry point of the program.

    • It initializes two SMA objects, h3 with a period of 3 and h5 with a period of 5.

    • A loop iterates through a pre-defined array v and adds each value to both SMA objects. It prints the original value, the SMA values for each object, and the updated SMA values.

    • Finally, it frees the memory allocated for the SMA objects.

In summary, this code demonstrates how to create and use an SMA library to calculate moving averages of a stream of values. It provides a flexible interface to perform common SMA operations, such as creating new objects, updating SMA calculations, and retrieving SMA values.

Source code in the c programming language

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

typedef struct sma_obj {
  double sma;
  double sum;
  int period;
  double *values;
  int lv;
} sma_obj_t;

typedef union sma_result {
  sma_obj_t *handle;
  double sma;
  double *values;
} sma_result_t;

enum Action { SMA_NEW, SMA_FREE, SMA_VALUES, SMA_ADD, SMA_MEAN };
sma_result_t sma(enum Action action, ...)
{
  va_list vl;
  sma_result_t r;
  sma_obj_t *o;
  double v;

  va_start(vl, action);
  switch(action) {
  case SMA_NEW: // args: int period
    r.handle = malloc(sizeof(sma_obj_t));
    r.handle->sma = 0.0;
    r.handle->period = va_arg(vl, int);
    r.handle->values = malloc(r.handle->period * sizeof(double));
    r.handle->lv = 0;
    r.handle->sum = 0.0;
    break;
  case SMA_FREE: // args: sma_obj_t *handle
    r.handle = va_arg(vl, sma_obj_t *);
    free(r.handle->values);
    free(r.handle);
    r.handle = NULL;
    break;
  case SMA_VALUES: // args: sma_obj_t *handle
    o = va_arg(vl, sma_obj_t *);
    r.values = o->values;
    break;
  case SMA_MEAN: // args: sma_obj_t *handle
    o = va_arg(vl, sma_obj_t *);
    r.sma = o->sma;
    break;
  case SMA_ADD: // args: sma_obj_t *handle, double value
    o = va_arg(vl, sma_obj_t *);
    v = va_arg(vl, double);
    if ( o->lv < o->period ) {
      o->values[o->lv++] = v;
      o->sum += v;
      o->sma = o->sum / o->lv;
    } else {
      o->sum -= o->values[ o->lv % o->period];
      o->sum += v;
      o->sma = o->sum / o->period;
      o->values[ o->lv % o->period ] = v; o->lv++;
    }
    r.sma = o->sma;
    break;
  }
  va_end(vl);
  return r;
}


double v[] = { 1, 2, 3, 4, 5, 5, 4, 3, 2, 1 };

int main()
{
  int i;

  sma_obj_t *h3 = sma(SMA_NEW, 3).handle;
  sma_obj_t *h5 = sma(SMA_NEW, 5).handle;

  for(i=0; i < sizeof(v)/sizeof(double) ; i++) {
    printf("next number %lf, SMA_3 = %lf, SMA_5 = %lf\n",
	   v[i], sma(SMA_ADD, h3, v[i]).sma, sma(SMA_ADD, h5, v[i]).sma);
  }

  sma(SMA_FREE, h3);
  sma(SMA_FREE, h5);
  return 0;
}


  

You may also check:How to resolve the algorithm Events step by step in the Racket programming language
You may also check:How to resolve the algorithm Sorting algorithms/Stooge sort step by step in the jq programming language
You may also check:How to resolve the algorithm Soundex step by step in the Groovy programming language
You may also check:How to resolve the algorithm Next highest int from digits step by step in the Factor programming language
You may also check:How to resolve the algorithm Formatted numeric output step by step in the DBL programming language