0

I have noticed a strange problem in C++ where when I add something together by "n" times it does not give the same output as multiplying by "n". Multiplying by "n" gives a better output. Adding by "n" times introduces more error.

For example, with the code below, recalculating length with a for loop of additions (lengthAdditionOutput) introduces greater error than by multiplication (recalculatedLength).

    //==================================
    DBG("original length: " << length);
    //==================================

float distancePerIncrement = length / samplePeriod;

int periodInteger = floor(samplePeriod);
float periodRemainder = samplePeriod - periodInteger;

float recalculatedLength = periodInteger * distancePerIncrement + (periodRemainder * distancePerIncrement);

    //==================================
    DBG("multiplied length: " <<  recalculatedLength << " difference: " << recalculatedLength - length);
    //==================================

lengthAdditionOutput = 0.f;

for (int i = 0; i < periodInteger; i++) {
    lengthAdditionOutput = lengthAdditionOutput + distancePerIncrement;
}
lengthAdditionOutput = lengthAdditionOutput + (periodRemainder * distancePerIncrement);

    //==================================
    DBG("added length: " << lengthAdditionOutput << " difference: " << lengthAdditionOutput - length);
    //==================================

The debug output will be for example:

original length: 0.931824 
multiplied length: 0.931824 difference: -5.96046e-08
added length: 0.93183 difference: 5.60284e-06

In other words, there is 100 times more error from addition than multiplication, and they are in opposite directions.

I note if I switch the floats to doubles the addition corrects and both methods output the same error (which is unchanged for the multiplication).

Is this normal behavior?

Thanks.

mike
  • 131
  • 10

0 Answers0