I am working with an array of doubles called indata
(in the heap, allocated with malloc), and a local double called sum
.
I wrote two different functions to compare values in indata
, and obtained different results. Eventually I determined that the discrepancy was due to one function using an expression in a conditional test, and the other function using a local variable in the same conditional test. I expected these to be equivalent.
My function A uses:
if (indata[i]+indata[j] > max) hi++;
and my function B uses:
sum = indata[i]+indata[j];
if (sum>max) hi++;
After going through the same data set and max
, I end up with different values of hi
depending on which function I use. I believe function B is correct, and function A is misleading. Similarly when I try the snippet below
sum = indata[i]+indata[j];
if ((indata[i]+indata[j]) != sum) etc.
that conditional will evaluate to true.
While I understand that floating point numbers do not necessarily provide an exact representation, why does that in-exact representation change when evaluated as an expression vs stored in a variable? Is recommended best practice to always evaluate a double expression like this prior to a conditional? Thanks!
double
value (typically 64 bits). In function A, the conditional expression may be evaluated using a higher precision (e.g. 80 bits). – Turret-mfpmath=sse
) on 32-bit code if you know it is supported by the target operating system and the processor in question, or to remove the extra rounding – Gd