Skip to content

Filter::mean() cannot compute a negative mean #4

@edgar-bonet

Description

@edgar-bonet

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions