#include
#include
main()
{
float i=0.0;
while(i!=1.0)
{
i+=0.1;
printf("%f",i);
}
getch(
}
why its output is infinite? Can anyone tell what should be done to make this finite ?
Answer
The loop is infinite because under a computer's floating-point arithmetic, adding 0.1 ten times is not equal to 1.
This is because computers use binary numbers to do arithmetic, and the number 0.1
cannot be expressed as a terminating binary number. So the computer has to pick a binary number that does terminate and that fits inside a float
as an approximation to 0.1. Unfortunately, it is imprecise enough that adding ten copies of this approximation together does not create a float that's equal to 1.
If you change the format string in your loop to show a much higher precision, you can see that the values of i
in the loop are not exact:
0.10000000149011611938
0.20000000298023223877
0.30000001192092895508
0.40000000596046447754
0.50000000000000000000
0.60000002384185791016
0.70000004768371582031
0.80000007152557373047
0.90000009536743164062
1.00000011920928955078
Generally, you should not compare floating-point numbers for equality. You can use inequality comparisons, check if two numbers are almost equal by whether their difference is smaller than some small fixed value of epsilon, or use integers for iteration and only convert to floating point when you need it. The other answers already explain these alternatives, so I won't go into them here.
No comments:
Post a Comment