0

I have the following code which minus 0.1 from 0.5 for 5 times, but the result isn't exact 0.0.

I understand why there is an error, and I'm finding a way to deal with it.

The only way I came up with is to check if abs(num - 0.0) < 0.01, but the 0.01 value may not be suitable in all situations (too big or too small).

Is there a more elegant way to deal with it?

#include <stdio.h>

int main() {
    double num = 0.5;

    for (int i = 0; i < 5; i++) {
        num -= 0.1;
    }

    printf("num=%lf %d", num, num == 0);
}
Pegasis
  • 1,256
  • 11
  • 15
  • 1
    https://floating-point-gui.de/errors/comparison/ – phuclv Apr 21 '20 at 16:44
  • 1
    I usually define `epsilon = 0.000001` or some similarly small number, then in place of `x == 0.0` I write `abs(x) <= epsilon`. It's not ideal, but there's not much else you can do. To use this, you need to have a good idea of the magnitudes of the numbers you're dealing with. – Tom Karzes Apr 21 '20 at 16:44
  • Sorry, I should have said `fabs` rather than `abs`, but you get the idea. – Tom Karzes Apr 22 '20 at 04:05

0 Answers0