-1

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 a 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 in 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;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
hh_l
  • 3
  • 2
  • Usually such artifacts are caused by the limited precision of floating point arithmetic. You should double check the result and maybe switch to a more numerically stable method of calculating your estimation. – Jakob Stark May 02 '22 at 15:33

1 Answers1

5

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?

ChrisMM
  • 8,448
  • 13
  • 29
  • 48