Email: Password: Remember Me | Create Account (Free)

Back to Subject List

Old thread has been locked -- no new posts accepted in this thread
???
08/14/02 19:38
Read: times


 
#27253 - RE: moving average
There are a couple of things I would do differently than Peter's example.

1. I would not sum the array each time I got a new sample. Instead, I would keep a running total and use the array to subtract out the oldest sample and add in the newest sample. This executes a lot faster.

2. I would not use the div_rnd(x,y) macro in the function. I'm really thinking that this is a boxcar average, but maybe I'm forgetting something. Either way, it is easy to add back in if it's necessary.

Other than that, our 2 algorithms are nearly identical.

Anyway, here it is. FYI, I didn't compile it or test it or anything.

#define SAMPLE_COUNT    16

/*-----------------------------------------------
Maintain STATIC copies of the sample table,
the index into it, and the current total.

sample_tab is simply an array of the last
SAMPLE_COUNT samples.

ndx is the index where the new_sample will go.

ttl is the total of all samples in sample_tab
(sample_tab[0] + sample_tab[1] + ...).
-----------------------------------------------*/
static int sample_tab [SAMPLE_COUNT];
static unsigned char ndx=0;
static long ttl = 0;

/*-----------------------------------------------
-----------------------------------------------*/
int moving_avg (
  int new_sample)
{
/*-----------------------------------------------
Subtract the oldest sample from ttl.
Add the new_sample to ttl and put the new_sample
into the sample_tab.
-----------------------------------------------*/
ttl += sample_tab [ndx];
ttl += new_sample;
sample_tab [ndx] = new_sample;

/*-----------------------------------------------
Increment the index and handle the ending
boundary.
-----------------------------------------------*/
if (++ndx >= SAMPLE_COUNT)
  ndx=0;

/*-----------------------------------------------
Return the average of the samples in the table.
-----------------------------------------------*/
return (ttl/SAMPLE_COUNT);
}



Jon

List of 12 messages in thread
TopicAuthorDate
moving average            01/01/70 00:00      
RE: moving average            01/01/70 00:00      
RE: moving average            01/01/70 00:00      
RE: moving average            01/01/70 00:00      
RE: moving average            01/01/70 00:00      
RE: Steve            01/01/70 00:00      
RE: moving average            01/01/70 00:00      
RE: moving average            01/01/70 00:00      
RE: Peter.            01/01/70 00:00      
RE: moving average            01/01/70 00:00      
RE: moving average            01/01/70 00:00      
RE: moving average            01/01/70 00:00      

Back to Subject List