3

By executing this code:

float f = 1.0;
while (f != 0.0) {
    f = f - 0.1;
    printf("%.1f\n", f);
}

It is expected that it would run 10 times and stop, but what turns out is that it inevitably goes into stack overflow. The same happens even if I change the while loop such that f goes to any other value below 1.0;

Anyone care to explain?

David Jones
  • 4,766
  • 3
  • 32
  • 45
CasualNoob
  • 41
  • 2

4 Answers4

3

It's dangerous to compare floats for equality/non-equality. float numbers are imprecise by nature because there are not enough bits to represent continuous nature of the float number.

Any time you compare floats, you should be comparing that the floats are within certain range of each other. For example:

while ((f - 0.0) > 0.00001)
Kon
  • 4,023
  • 4
  • 24
  • 38
2

Why did code loop forever?

Typical float can represent about 232 numbers exactly, 0.1 is not one of them. So code is more like.

float f = 1.0;
while (f != 0.0) {
  f = f - a_number_close_to_one_tenth;
  printf("%.1f\n", f);
}

The repeated subtractions "miss" 0.0.


Instead use >= and code will iterate the expected number of times (or maybe once more). Use a higher precision print to see why.

float f = 1.0;
while (f >= 0.0) {
  f = f - a_number_close_to_one_tenth;
  printf("%.17e\n", f);
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
1

It is a floating point issue. Try > instead of !=

float f = 1.0;
while (f > 0.0) {
    f = f - 0.1;
    printf("%.1f\n", f);
}
Kevin Vandy
  • 401
  • 3
  • 10
0

Loops should better never be done on floating points.
It's even required by some coding standards like rule FLP30-C at https://wiki.sei.cmu.edu/confluence/display/c/FLP30-C.+Do+not+use+floating-point+variables+as+loop+counters

B. Go
  • 1,436
  • 4
  • 15
  • 22