runningMedian class on playground

robtillaart:
very nice addition, code can be simpler

  • if (_cnt > nMedians) implies _cnt > 0 for all _nMedians
  • there is no check for nMedians == 0;
[snipped, see thread above]

think even
if (_cnt >= nMedians)
is valid

so it could become

[snipped, see thread above]

what you think?

Good thoughts. Though I'd probably make the following (minor) change for both consistent style and to trap accidentally trying to pass a negative value for nMedians: (on second thought, only for consistent style as uint8_t can't be negative...)

float RunningMedian::getAverage(uint8_t nMedians)
{
	if (nMedians > 0)
	{
		if (_cnt < nMedians) nMedians = _cnt;     // when filling the array for first time
		uint8_t start = ((_cnt - nMedians)/2);
		uint8_t stop = start + nMedians;
		sort();
		float sum = 0;
		for (uint8_t i = start; i < stop; i++) sum += _as[i];
		return sum / nMedians;
	}
	return NAN;
}

BTW, when converting my program back from the template version to the regular cpp and h version for my new method, I noticed that the template version added some new methods (one of which I was using which is why I noticed it):

getSize
getCount
getStatus

I don't think the getStatus method is useful outside the template version, but both getSize (returns _size) and getCount (returns _cnt) are useful for troubleshooting. They could also be used by a programmer to make sure they have enough statistics to get proper results, especially if they clear the array often.