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?
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)
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With