Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: while loop using floating point never terminates [duplicate]

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?

like image 765
CasualNoob Avatar asked Nov 20 '25 11:11

CasualNoob


2 Answers

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)
like image 146
Kon Avatar answered Nov 23 '25 00:11

Kon


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);
}
like image 39
chux - Reinstate Monica Avatar answered Nov 23 '25 01:11

chux - Reinstate Monica