-3

I need help with a problem regarding exponential smoothing in C++

The smoothing follows this equation :

newValue = inputSignal*smoothFactor + (1-smoothFactor)*oldValue

My function is supposed to only have one input parameter, that is the inputSignal parameter (the smoothFactor can be declared within the function and is not subject of the problem) and one output parameter, that is the newValue.

Now the issue I am having is that the FIRST calculation is missing an oldValue, since the oldValue is the preceding newValue in the first function call.

So the oldValue has to equal the first inputSignal in the first function call.

That means my function needs to behave different in its first call than every following call. I can solve this if I declare a global i=0 parameter and count up i++ after the first call. This however is NOT a function independent of outside circumstances, which it should be.

I was able to solve the problem with the i=0 and i++ global variables, but fail to find a solution without this.

Niall
  • 30,036
  • 10
  • 99
  • 142
  • 1
    A larger code sample would help here – Niall Oct 10 '14 at 07:06
  • Turn this into a utility class. Your function has internal state (oldValue, probably local static?) which is usually a bad idea. You can then have an extra bool member in your class to detect the first call. Also, simply return newValue rather than making it an output parameter. – heinrichj Oct 10 '14 at 07:15

1 Answers1

3

You can use a local static variable in the function (cf this question). Local static variables are initialized exactely once on the first invocation of the method. So you can use this:

double smooth(double inputSignal) {
    static double oldValue = inputSignal; // Executed only once on first invocation
    double newValue = inputSignal*smoothFactor + (1-smoothFactor)*oldValue;
    oldValue = newValue; // Store it for next invocation
    return newValue;
}
Community
  • 1
  • 1
king_nak
  • 11,313
  • 33
  • 58