Consider the following code:
#include<stdio.h>
#define k 0.7
#define p 0.5
int main()
{
float a=k,b=p;
double aa=k;
if(a<k)
{
if(b<p) printf("2 is right");
else printf("1 is right");
}
else printf("0 is right");
printf("\n");
if(a>k)
{
if(b<p) printf("2 is right");
else printf("1 is right");
}
else printf("0 is right");
return 0;
}
Consider this as part II of this question, here the understanding was that the double precision values of floating point constants (doubles when represented as numeric constants) was lost when it was converted to their corresponding floating point values. The exceptional values were X.5 and X.0. But I observed the following results:
Input Output
K=0.1 to 0.4 0 is right
1 is right
K=0.5 0 is right
1 is right
K=0.6 0 is right
1 is right
K=0.7 1 is right
0 is right
K=0.8 0 is right
1 is right
K=0.9 1 is right
0 is right
K=8.4 1 is right
0 is right
Why is this queer behavior? How come only few floating point values are displaying this property? Can’t we assume that float precision values are always less than double precision values?? How do we explain this behavior?
Not really, they may both have the same precision. You can assume that the range and precision of
doubleis not smaller than that offloat.But, for all practical purposes, it’s a profitable bet that
doublehas 53 bits of precision andfloathas 24. And thatdoublehas 11-bit exponents,float8-bit.So, disregarding exotic architectures,
floathas less precision and a smaller range thandouble, everyfloatvalue is representable as adouble, but not vice versa. So casting fromfloattodoubleis value-preserving, but casting fromdoubletofloatwill change all values needing more than 24 bits of precision.The cast is generally performed (for values in the
floatrange) by rounding the significand of thedoublevalue to 24 bits of precision in the following way:You cannot predict if casting a
doubletofloatincreases or decreases the value by looking at the decimal expansion, except in the few cases where you can see that the value will be unchanged. It’s the binary expansion that matters.