The program
#include <Filter.h>
void setup() {
Filter filter(3);
filter.write(-3);
filter.write(-5);
filter.write(-7);
Serial.begin(9600);
Serial.print("mean(-3, -5, -7) = ");
Serial.println(filter.mean());
}
void loop(){}
outputs
mean(-3, -5, -7) = 143165572
This is due to the (scaled) mean being computed as
long mean = sum / _values.available();
where sum is of type long and _values.available() is unsigned long. According to the C++ rules on usual arithmetic conversions, evaluating the above expression involves an implicit cast of sum to unsigned long, hence the wrap around.
The obvious fix is to change _values.available() to be of any type among long, int, short or unsigned short.
The program
outputs
This is due to the (scaled) mean being computed as
long mean = sum / _values.available();where
sumis of typelongand_values.available()isunsigned long. According to the C++ rules on usual arithmetic conversions, evaluating the above expression involves an implicit cast ofsumtounsigned long, hence the wrap around.The obvious fix is to change
_values.available()to be of any type amonglong,int,shortorunsigned short.