RobTillaart / RunningAverage

Arduino library to calculate the running average by means of a circular buffer.
MIT License
53 stars 10 forks source link

getStandardDeviationLast(uint16_t count) #31

Closed alvaro-oliver closed 3 months ago

alvaro-oliver commented 3 months ago

Would you consider implementing this? I'm working on a project based on average and standard deviation at different buffer lengths. This would save me lots of RAM. Thanks!

RobTillaart commented 3 months ago

Thanks for the request, A non optimized version should be not too difficult to implement. Need to find some time to give it a try.

RobTillaart commented 3 months ago

A quick implementation, not tested.

Add this in your .cpp file

float RunningAverage::getStandardDeviationLast(uint16_t count) const
{
  uint16_t cnt = count;
  if (cnt > _count) cnt = _count;
  if (cnt <= 1) return NAN;

  float temp = 0;
  float average = getAverageLast(count);
  uint16_t idx = _index;
  for (uint16_t i = 0; i < cnt; i++)
  {
    if (idx == 0) idx = _size;
    idx--;
    temp += pow((_array[idx] - average), 2);
  }
  temp = sqrt(temp/(cnt - 1));
  return temp;
}

and a signature in your .h file

float getStandardDeviationLast(uint16_t count) ;

please give it a try if this works for you

RobTillaart commented 3 months ago

@alvaro-oliver Added the above function to the develop branch of for the 0.4.6 version. Please verify if it meet your needs.

RobTillaart commented 3 months ago

Added function to version 0.4.6

Thanks again for the idea!

alvaro-oliver commented 3 months ago

Thanks a lot, Rob!. I'm sorry for the delay, but I've just tested and it works great, just needed to add "const" to the .h file prototype to match your .cpp function declaration. This is the output for my test sketch:

Added: 1.000
Added: 2.000
Added: 3.000
Added: 4.000
Added: 5.000
Added: 6.000
Added: 7.000
Added: 8.000
Added: 9.000
Added: 10.000

Total Average: 5.500
Total Stdev. (sample): 3.028

Last five Average: 8.000
Last five Stdev. (sample): 1.581
Ended...
alvaro-oliver commented 3 months ago

I didn't realized you already merged into a new version. Work flawless, this is the output on 0.4.6:

RUNNINGAVERAGE_LIB_VERSION: 0.4.6
Added: 1.000
Added: 2.000
Added: 3.000
Added: 4.000
Added: 5.000
Added: 6.000
Added: 7.000
Added: 8.000
Added: 9.000
Added: 10.000

Total Average: 5.500
Total Stdev. (sample): 3.028

Last five Average: 8.000
Last five Stdev. (sample): 1.581
Ended...

Thanks again!

RobTillaart commented 3 months ago

No need to apologize, it is good to hear that you can confirm that it works as intended.

I will check your note on const asap. Will not make a new release for that now.

RobTillaart commented 3 months ago

@alvaro-oliver

Can you share you test code?