1
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!!

kareem20
  • 21
  • 6
  • 6
    Probably a floating point error...[Is floating point math broken?](//stackoverflow.com/q/588004) – 001 May 11 '18 at 20:45
  • Most likely your `double` is not exactly zero, so the condition fails. See [What Every Programmer Should Know About Floating-Point Arithmetic](http://www.phys.uconn.edu/~rozman/Courses/P2200_15F/downloads/floating-point-guide-2015-10-15.pdf) all derived from [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html); and [Originalpdf](http://www.itu.dk/~sestoft/bachelor/IEEE754_article.pdf) – David C. Rankin May 11 '18 at 20:45
  • Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – DeiDei May 11 '18 at 20:46
  • `-0` can give useful information in some cases. – Weather Vane May 11 '18 at 20:54
  • @chux has previously commented on this topic, perhaps he can improve my comment. It is not necessarily about inexact values, but an exact `+0` or `-0`. – Weather Vane May 11 '18 at 21:01
  • what difference between +0 and -0? – kareem20 May 11 '18 at 21:38

1 Answers1

2

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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278