1

So I'm wondering, how do I make sure that all steps in a loop are performed if the step size is smaller than 1? Take this loop for instance:

for (float y, x = -1.0; x <= 1.0; x += 0.1) {         
    y = (4*x*x*x) + (3*x*x) + (5*x) - 10;
    printf("x = %.2f, y = %.2f\n", x, y);

}

Output:

x = -1.00, y = -16.00
x = -0.90, y = -14.99
x = -0.80, y = -14.13
x = -0.70, y = -13.40
x = -0.60, y = -12.78
x = -0.50, y = -12.25
x = -0.40, y = -11.78
x = -0.30, y = -11.34
x = -0.20, y = -10.91
x = -0.10, y = -10.47
x = 0.00, y = -10.00
x = 0.10, y = -9.47
x = 0.20, y = -8.85
x = 0.30, y = -8.12
x = 0.40, y = -7.26
x = 0.50, y = -6.25
x = 0.60, y = -5.06
x = 0.70, y = -3.66
x = 0.80, y = -2.03
x = 0.90, y = -0.15

I intend the loop to also run for x = 1, but as you can see it doesn't do that. I've heard that it's not safe to use floats as loop counters, as the float precision isn't exact. The fact that I'm using a float variable as the loop counter is probably the cause of my problem. So what solutions are there to my problem? Thanks in advance for your kind responses!

1 Answers1

1

The problem, as you noted, is that you shouldn't use floats as loop counters. So multiply everything by 10 and use integers:

for (int x = -10; x <= 10; ++x) {
  float y = (0.004*x*x*x) + (0.03*x*x) + (0.5*x) - 10;
  printf("x = %.2f, y = %.2f\n", 0.1*x, y);  
}

Produces:

x = -1.00, y = -16.00
x = -0.90, y = -14.99
x = -0.80, y = -14.13
...
x = 0.90, y = -0.15
x = 1.00, y = 2.00

as expected.

Perhaps even better: logically separate your loop variable from the meaningful stuff.

 for(int i = -10; i <= 10; ++i) {
    float x = 0.1 * i;
    float y = (4*x*x*x) + (3*x*x) + (5*x) - 10;
    printf("x = %.2f, y = %.2f\n", x, y);    
}
CompuChip
  • 9,143
  • 4
  • 24
  • 48