Search code examples
clapacke

Why is this condition not satisfied ?


printf("Elements of vector U:\n");
rprint_vector(u, n); 
double vt = dasum_(&n, u, &incx);
printf("vt = %lf\n", vt);

if (vt == 0)
    printf("yes vt = 0\n");
else
    printf("No vt != 0\n");

Results :

Elements of vector U:
------------
0.000000
0.000000
-0.000000
0.000000
------------
vt = 0.000000
No vt != 0

even though the variable vt equal to 0 the condition is not satisfied. where is the problem!!


Solution

  • This is the nature of finite precision representation.

    I'll use an analogy with fixed-precision decimal representation. You represent 1/3 as 0.333333 and 2/3 and 0.666667. So if you do 2/3 - 1/3 - 1/3, the result will be 0.000001. You will probably display that as 0.000, since there's not much point in displaying any more digits. But it's not precisely equal to zero.

    Don't compare floating point numbers that way because the answer will switch from yes to no with even the slightest imprecision. If you want to write an "is very, very close to" function, do so.