I work with an array of doubles called indata (on the heap allocated by malloc) and a local double name sum .
I wrote two different functions for comparing values in indata and got different results. In the end, I decided that the discrepancy is due to one function that uses the expression in the conditional test, and the other function uses the local variable in the same conditional test. I expected them 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 dataset and max , I get different hi values depending on the function used. I believe that 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 the conditional value will be true.
Although I understand that floating point numbers do not necessarily provide an accurate representation, why does this exact representation change when evaluated as a vs expression stored in a variable? Is it best to use a double expression like this before the conditional? Thank you
c syntax floating-point floating-accuracy expression
stilllearning
source share