0

Here is the code I am trying to run.

int main() {
    double dx=0.1, p=-10;
    double x[200];
    int i=0;
    while (p<=10) {
        if (p==0) {
            p=p+dx;
        }
        x[i]=p;
        i++;
        p=p+dx;
    }
    for (i=0; i<200; i++) {
        printf("%lf ", x[i]);
    }
    return 0;
}

I want the array x to contain numbers from -10 to 10 with an increment of 0.1 but excluding zero. However, this program is saving -0.0 in the array x[]. The if condition is coming out to be false for some reason. The program works for an increment of 0.25.

How can I change this code for a 0.1 increment?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Ritik Pal
  • 11
  • 2
  • You should never do exact comparisons against doubles. See https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Alexander Jul 29 '22 at 16:59
  • You should run an `int` variable from -100 to 100, with an `if` statement to skip 0, then multiply by `dx` before storing into your array. – Steve Summit Jul 29 '22 at 17:03
  • If you're still puzzled, think about what would happen if you set `dx = 0.3333333333`. You wouldn't be surprised if you had the same problem, that is, if the condition always came out to be false, that is, if `p` was never quite exactly equal to 0. Well, that's exactly what's happening here, because it turns out that in binary, 1/10 is an infinitely-repeating fraction also, namely `0b0.00011001100110011011…`. – Steve Summit Jul 29 '22 at 17:07
  • *How can i change this code for a 0.1 increment?* You should run an `int` variable from -100 to 100, with an if statement to skip 0, then multiply by `dx` before storing into your `x` array. For example, `23 * 0.1` gives `2.3`. – Steve Summit Jul 30 '22 at 04:32
  • thnks for your help everyone. – Ritik Pal Jul 31 '22 at 08:48

1 Answers1

1

The value 0.1 cannot be represented exactly in binary floating point. So what you'll have instead is a close approximation of it, which means every addition will also be an approximation of the result. So when you get to "0" it's not actually 0 but close to 0.

In contrast, 0.25 can be represented exactly, so adding that value also gives you an exact result.

dbush
  • 205,898
  • 23
  • 218
  • 273