C++ - Sum output different depending on elements order

Viewed 67

While trying to parallelize a code in C++, I observed that the results changes every time I run the code. Investing within the code, I dind't find any issue and, at the contrary, I noticed that inverting the order with which I sum some numbers the resulting sum changes.

An example is shown below, in which I take the same numbers in a different order and I calculate the sum (simulating a loop).

int main()
{
     double XX1 = 0;
     XX1 = XX1 + 364.29129656036;
     XX1 = XX1 + 364.363465344009;
     XX1 = XX1 - 364.29129656039;
     XX1 = XX1 - 364.363465344038;

     double XX2 = 0;
     XX2 = XX2 - 364.29129656039;
     XX2 = XX2 - 364.363465344038;
     XX2 = XX2 + 364.29129656036;
     XX2 = XX2 + 364.363465344009;

     cout.precision(27);
     cout << XX1 << endl;
     cout << XX2 << endl;

`    return 0;
}

XX1 = -5.89466253586579114198684692e-11
XX2 = -5.88897819397971034049987793e-11

Do you know if:

  • Is this normal?
  • Is there a way to avoid it? Consider that, because of parallelisation, the sum will be done in a "random" order, so there is no way to follow always the same order.

Thanks in advance.

0 Answers
Related