C++: For two different functions with do-while loops, why does x+=y give the same result as x=x+y in one function but not the other?

For function A below, I get a different result when I use "est += XXX" as compared to using "est = est + XXX". The former gives a result of 1.33227e-15 while the latter gives an result of 8.88178e-16.

On the other hand, for function B below, I get the same result regardless of whether I use "est += XXX" or "est = est + XXX"

Would anyone be able to explain why x+=y is equivalent to x=x+y in function B but not A?

function A

double A(int nTerm){
        const double PI = 3.141592653589793238463;    
        double est = 0;
        double counter = 0;

    do {
        est += ( 16 * pow(-1,counter) )/ (2*counter+1) * pow((double)1/5, 2*counter+1) 
             - ( 4 * pow(-1,counter) )/ (2*counter+1) * pow((double)1/239, 2*counter+1);
        counter++;  
        } while (counter<=nTerm);
    
        return est-PI;
    }

function B

double B(int nTerm){
        double est = 0;
        double counter = 0;

    do {
        est += counter;
        counter++;  
    } while (counter<=nTerm);

    return est;
    }

>Solution :

x += y - z is the equivalent to x = x + ( y - z ). You likely wrote x = x + y - z. You need to enforce precedence. See here that with the brackets, the return values are the same.

In your case, you want:

est = est + ( ( 16 * pow(-1,counter) )/ (2*counter+1) * pow((double)1/5, 2*counter+1) 
             - ( 4 * pow(-1,counter) )/ (2*counter+1) * pow((double)1/239, 2*counter+1) );

Note: when dealing with double values, A + B - C can be very different than A + ( B - C ) even though they should be the same. See Is floating point math broken?

Leave a Reply