2

I have a strange problem with fabs function in C code. I have two double values and I want to find the absolute value of their difference using code like this:

a = 87.967498;
b = 218.025015;
if (fabs(a-b)<2.0)
...code to execute

The value of fabs(a-b) is an int and is equal to 1. I don't know whats the problem here and I can't find anything on the net. Any help would be great!!

  • Also, you might have to link the math.h manually. See: http://stackoverflow.com/questions/1033898/why-do-you-have-to-link-the-math-library-in-c – SBI Jan 14 '13 at 10:03
  • A `fabs` macro maybe? Do a `grep -w fabs *.c *.h` to check – Déjà vu Jan 14 '13 at 13:01
  • hi @Przemysław, have you figure out the problem ? I remember I had the same problem. it went away after I clean everything and made a fresh build of my project. – TMS Sep 19 '16 at 17:38

3 Answers3

3

You didn't include <math.h>. Add the following line to your other includes:

#include <math.h>

In order to find such errors easier I recommend you to use verbose compiler warnings (gcc -Wall -Wextra ... if you use gcc).

Zeta
  • 103,620
  • 13
  • 194
  • 236
2

The only way that fabs could return an int is either:

  • Your program uses a declaration of fabs other than the version declared in math.h.
  • Your program failed to include math.h and so does not declare fabs at all. In which case parameters and return values default to int. Which is of course an error because the actual implementation of fabs does not match and so the value returned is nonsense.
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 1
    The code I posted is a part of a large program using a lot of `math.h' methods and they work fine, because the whole program works generally fine. Of course except this small piece of code. – Przemek Jacewicz Jan 14 '13 at 10:02
0

See this code:

#include <math.h>
#include <stdio.h>

int main()
{
    float a = 87.967498;
    float b = 218.025015;
    float diff = a-b;

    printf("diff=%f\nfabs(diff)=%f\n",diff,fabs(diff));
    if (fabs(diff)<2.0) {
        printf("OK\n");
    } else {
        printf("FAIL\n");
    }

    return 0;
}

It produces this output:

diego@malti:~/tmp$ clang test-math.c -o test-math -lm
diego@malti:~/tmp$ ./test-math 
diff=-130.057510
fabs(diff)=130.057510
FAIL

See? The application is OK, the diff (218-87=130), which is not smaller then 2.

See also then when I am compile, I also link -lm to get the mathematical library. The same syntax applies for gcc, I just love using clang :)

elcuco
  • 8,948
  • 9
  • 47
  • 69
  • I compiled that code and got the same output (well, except user@machine stuff...) However, when I run it under gdb I get this: ` (gdb) p fabs(diff) $1 = 1 (gdb) p diff $2 = -130.05751` – Ale Aug 22 '18 at 10:16