This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Floating point comparison
When I run the code below I get the following output:
Output : if
Why does this happen?
#include <stdio.h>
void main()
{
float a = 0.7;
if(a<0.7)
{
printf("if");
}
else
{
printf("Else");
}
}
Your program compares the double representation of 0.7 (which is what the compiler produces when you write 0.7 in your program) with a float representation of 0.7 (which is what variable a contains). The two are not the same, and it just happens that the double one is slightly larger.
EDIT: (float)0.7 can be represented compactly in hexadecimal notation. It is 0x1.666666p-1. 0.7 as a double constant is 0x1.6666666666666p-1, so it is slightly larger.
Floating points are not stored in precise format. Most likely, your platform interprets
float a = 0.7;
as
float a = 0.69999....;
This is because of the internal representation of floating points on your platform. The link provided by Daniel should get you started.
That is due to accuracy issues in floating point representation on a computer. See this Wikipedia article.
Related
This question already has answers here:
strange output in comparison of float with float literal
(8 answers)
Closed 6 years ago.
float f=2.2;
if (f==2.2)
printf("abc");
else
printf("xyz");
This code prints xyz,while if we give 2.5 instead of 2.2 the output is abc.
2.2 is a double that is not exactly representable in binary floating point. In effect, you are comparing the double 2.2 to the result of converting it to float, with rounding, and then back to double.
Assuming double is IEEE 754 64-bit binary floating point, and float is IEEE 754 32-bit binary floating point, the closest double to decimal 2.2 has exact value 2.20000000000000017763568394002504646778106689453125, and the result of converting it to float is 2.2000000476837158203125. Converting the float back to double does not change its value. 2.20000000000000017763568394002504646778106689453125 is not equal to 2.2000000476837158203125.
2.5 is exactly representable in both float and double in binary floating point systems, so neither the conversion to float nor the conversion back to double changes the value. 2.5 is equal to 2.5.
Floating-point numbers are likely to contain round-off error
Ref: http://www.cs.yale.edu/homes/aspnes/pinewiki/C(2f)FloatingPoint.html
Going through the documentation,
I see the following. (Point 6 in the URL above)
In general, floating-point numbers are not exact: they are likely to contain round-off error because of the truncation of the mantissa to a fixed number of bits.
The easiest way to avoid accumulating error is to use high-precision floating-point numbers (this means using double instead of float). On modern CPUs there is little or no time penalty for doing so....
One consequence of round-off error is that it is very difficult to test floating-point numbers for equality, unless you are sure you have an exact value as described above. It is generally not the case, for example, that (0.1+0.1+0.1) == 0.3 in C. This can produce odd results if you try writing something like for(f = 0.0; f <= 0.3; f += 0.1): it will be hard to predict in advance whether the loop body will be executed with f = 0.3 or not. (Even more hilarity ensues if you write for(f = 0.0; f != 0.3; f += 0.1), which after not quite hitting 0.3 exactly keeps looping for much longer than I am willing to wait to see it stop, but which I suspect will eventually converge to some constant value of f large enough that adding 0.1 to it has no effect.)
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 6 years ago.
I'm getting an unexpected behaviour when comparing a float value, I understand that floats could have rounding precission issues but here numbers are quite specific to present those issues.
#include <stdio.h>
int main()
{
float alpha = 0.0f;
int finish = 0;
while (finish == 0)
{
alpha += 0.05f;
if (alpha > 1.0f)
{
printf("%f", alpha); // Expected result: 1.05f, actual result: 1.0f
finish = 1;
}
}
return 0;
}
Actually, condition enters when alpha = 1.0f. Can't understand that behaviour...
I'm compiling with MinGW (GCC 5.3.0) on Windows 10 (tested on 32bit and 64bit), Intel i5 processors.
(Restricting the answer if I may to IEEE754 floating point).
There is no such float as 0.05. The nearest number representable to that is
0.0500000007450580596923828125
So what is happening, is that slightly larger values than what you think are added to alpha, which is enough to just push it over the 1.0f mark (which, out of interest, can be represented exactly.)
The default formatting in print is rounding that slightly greater than 1.0f number back to 1.0f.
In summary, all this is due to binary floating point not having, in general, an exact decimal representation.
This question already has answers here:
strange output in comparison of float with float literal
(8 answers)
Closed 9 years ago.
Please explain the output for different cases
#include<stdio.h>
int main()
{
float a=5.9; //a=0.9
if (a==5.9)
printf("Equal");
else if (a<5.9)
printf("Less than");
else
printf("Greater than");
return 0;
}
When a is 5.9 the output is "Greater than", when a is 0.9 the output is "Less than". Why?
In C, the literal “5.9” has type double and is converted by common compilers to 5.9000000000000003552713678800500929355621337890625, because they use binary IEEE-754 floating point, and that number is the value representable as a double that is closest to 5.9. Your code initializes a float with that value. That requires converting a double to a float, and the result is 5.900000095367431640625, because that is the float value that is closest to the double value. Obviously, the latter is greater than the former, which is why your output is “Greater than”.
With .9, the literal “.9” is converted to the double 0.90000000000000002220446049250313080847263336181640625. Then that double is converted to the float 0.89999997615814208984375, which is obviously less than the double.
Your variable is a float but the constant is a double. Since that value can't be stored precisely ti will be stored differently as a float and as a double. If you use the same data types you'll get the desired results
http://codepad.org/1q5mwFGd
http://codepad.org/Q4lOQnG8
Floating point numbers are inherently imprecise. For a quick introduction, you can read up a bit here. http://floating-point-gui.de/errors/comparison/
For some suggestions on effective comparison strategies, see this post. What is the most effective way for float and double comparison?
This is because internally, the floating point numbers are stored in binary form and 5.9 can't be represented exactly as 5.9. Have a look at the following similar question and answer: Why does a C floating-point type modify the actual input of 125.1 to 125.099998 on output?
When comparing floating-point numbers it is best to avoid '=='.
This because some values cannot be correctly stored without some loss of precision.
So it is better to say:
if( fabs(a-5.9) < .0001 ) {
// 'EQUAL' or at least near enough!
}
I know this takes more to compute, but it will behave the way you expect.
Due to decimal binary conversion, 0.9 represented as a summation of powers of 2^-1:
0.9 - (0.5 + 0.25 + 0.125) = 0.025
But 0.025 is not an exact power of 2^-1. So you need to represent both numbers in the comparison with the same precision. Since float and double have different precision they compare not equal.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
strange output in comparision of float with float literal
Here is the code
#include<stdio.h>
int main()
{
float a=0.3;
if(a==0.3)
printf("Hello World!");
else
printf("Stack Overflow");
return 0;
}
I expected output as "Hello World". But i got "Stack overflow". Why I didnt get "Hello World"?
Is there anything wrong in the if condition?
Comparing floating point numbers
Floating point math is not exact. Simple values like 0.2 cannot be precisely represented using binary floating point numbers, and the limited precision of floating point numbers means that slight changes in the order of operations can change the result. Different compilers and CPU architectures store temporary results at different precisions, so results will differ depending on the details of your environment. If you do a calculation and then compare the results against some expected value it is highly unlikely that you will get exactly the result you intended.
Try this way:
#include<stdio.h>
int main()
{
float a=0.3;
float acceptedDiff = 0.0000001;
if(fabsf(a-0.3) < acceptedDiff)
printf("Hello World!");
else
printf("Stack Overflow");
return 0;
}
Try that :)
if (a == 0.3f)
or
if (a == (float)0.3)
Floating point values shall not be compared using either the == or != operators.
Most floating point values have no exact binary representation and have a limited precision. See what you can do.
It is because values like 0.3 cannot be precisely represented using binary floating point numbers. Temporary values are stored differently and thus cannot be compared liike this.
The value for a and 0.3 are thus stored differently and you cannot rely on such a direct comparison.
It is because of precision issue..This tutorial might interest you..
Yes as far as i know while the IF statement compare the variables and values it goes into the machine level information and storage of the value.
very first line you declared a = 0.3 as float type and so it will be stored in the binary format in the memory with the extra padding of the bits. and when you compare it with Exact "0.3" it will always fail.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
problems in floating point comparison
#include <stdio.h>
#include <conio.h>
main()
{
float a = 0.7;
if(a < 0.7)
printf("C");
else
printf("C++");
}
In the above code, the output is C. I tried this code in Code::Blocks and Pelles C but got the same answer. I would like know the reason for this in detail!
In binary, 0.7 is:
b0.1011001100110011001100110011001100110011001100110011001100110...
However, 0.7 is a double-precision literal, whose value is 0.7 rounded to the closest representable double-precision value, which is:
b0.10110011001100110011001100110011001100110011001100110
In decimal, that's exactly:
0.6999999999999999555910790149937383830547332763671875
When you write float a = 0.7, that double value is rounded again to single-precision, and a gets the binary value:
b0.101100110011001100110011
which is exactly
0.699999988079071044921875
in decimal.
When you do the comparison (a < 0.7), you are comparing this single-precision value (converted to double, which does not round, because all single-precision values are representable in double precision) to the original double-precision value. Because
0.699999988079071044921875 < 0.6999999999999999555910790149937383830547332763671875
the comparison correctly returns true, and your program prints "C".
Please note that none of this is any different in C++, appearances of the code in question to the contrary. There are certain (numerically unsafe) compiler optimizations that can change the behavior, but those are not unique to C or C++.
It's because 0.7 has type double, so a gets converted to double and comparison is made in this type. As 0.7 is not representable exactly in binary floating-point, you get some rounding error and the comparison becomes true.
You can:
if( a < 0.7f ) {
....
But actually this effect is true for C++ too, so your conditional is not exactly rightful.
Bart gave a very good reference in his comment, but I would also recommend this very simple rule:
Not all numbers can be represented exactly in the computer, so as soon as you use floating point numbers (such as float and double), you should expect that there can be a small, unpredictable error in each stored number. No, it isn't really random or unpredictable, but until you know more about it you can consider it unpredictable. Therefore, a copmparison such as your a<0.7 might turn out to be true, and it might not. Don't write code that depends on it being either.