View Full Version : Again mystry outputs
adarshakb
07-01-2010, 12:27 PM
:eek: I cant understand this can someone enligten me how floating point numbers are stored?
void main()
{
float a=0.7;
if(a<0.7)
printf("C");
else
printf("C++");
}
Output:
C
BUTTTT
void main()
{
if(0.7<0.7)
printf("C");
else
printf("C++");
}
Output:
C++
:confused::confused::confused::confused:
I am using Visual studio 2008 if that helps
BrickInTheWall
07-01-2010, 03:03 PM
Look at this article:
http://steve.hollasch.net/cgindex/coding/ieeefloat.html
Thing is, even if you set a to be 0.7, it's not EXACTLY 0.7 since the accuracy of floating point numbers is limited. You should look for some tutorials on floating point arithmetic, as it is very important.
adarshakb
07-01-2010, 07:41 PM
Look at this article:
http://steve.hollasch.net/cgindex/coding/ieeefloat.html
Thing is, even if you set a to be 0.7, it's not EXACTLY 0.7 since the accuracy of floating point numbers is limited. You should look for some tutorials on floating point arithmetic, as it is very important.
Ya i knew all those! and i worked it out.... here it is
sign=0
0.7 in binary = 0.101100110011001100....(1100 is repeating here)
this mantisa part= 0.10110011001100=in normalized form 1.0110011001100*2^-1
Exponent part=-1+127=126= 01111110
Mantissa part =
01100110011001100110011 ----->(23bits)
therefore out 0.7 is
00111111001100110011001100110011 -----in float
IN DOUBLE now
sign=0---- 1 bit
Exponent= 00001111110 ---- 11bits
Mantissa=011001100110011001100110011001100110011001100110011001100110
Hence 0.7 in Double is
000001111110011001100110011001100110011001100110011001100110011001100110
Here is the Problem now:p:D
a<0.7
What Happens is THIS i believe
0.7 is treated as DOUBLE
a is float so its converted to double...
Extra bits in sign as covered with 0s so that value remains same. This is done by prefixing Exponent with 0s and postfixing Mantissa with 0s
Sign -MATCHS 0=0
Exponent - MATCHES 01111110=00001111110
Mantissa -- is as follows
a's : Converted to
0011111100110011001100110011001100000000000......(fill it up with 0)
but 0.7's is 011001100110011001100110011001100110011001100110011001100110
(I might have missed a few 0s lol but no patience to check)
so this is what its adjudec "true" when a<0.7 is calculated
:thumbsup::thumbsup::thumbsup:
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.