I have two vectors of double. The value of the double is between -1000 and 1000.
Both vectors contain the same numbers, but the order is different.
For example
Vector1 = {0.1, 0.2, 0.3, 0.4};
Vector2 = {0.4, 0.2, 0.1, 0.3};
Is there a guarantee that the sum of Vector1 will be exactly equal to the sum of Vector2, assuming the sum is done via:
double Sum = 0;
for (double Val : Vector) Sum += Val;
I am worried about double imprecisions.
>Solution :
Is there a guarantee that the sum of Vector1 will be exactly equal to the sum of Vector2, assuming the sum is done via:
No, there is no such guarantee in the C++ language.
In fact, there is an indirect practical guarantee – assuming typical floating point implementation – that the results would be unequal. (But compilers have ways of disabling such guarantees, and of enabling unsafe floating point optimisations that may cause the sum to be equal).
The difference is likely to be very small with the given input, but it can be very large with other inputs.