In article <ba**************************@posting.google.com >,
ke***@parikh.com (Ketan Parikh) wrote:
Hey everybody,
I am new to this group. I am from India.
Consider the following code.
main()
{
float k=0.7;
if (k < 0.7)
printf("Hey");
else
printf("Hello");
}
the o/p of the program is: "Hello" why?
I have tried also with 0.1,0.2 ...0.9
but only in 0.7 and 0.9 case i have got o/p as "Hello"
and in all other cases i have got o/p as "Hey".
so please give me reason about this answer?
When you write 0.7 you get a floating-point value in double precision
that is very close to the real number 0.7; the difference is probably
much less than 1e-15.
When you write float k = 0.7 then you get a floating-point value in
single precision that is relatively close to the real number 0.7; the
difference is probably something around 1e-7. The double precision value
gets rounded to much lower single precision.
When a number gets rounded from double to float, then some values get
rounded up, some values get rounded up. There are some rare values that
stay unchanged: Most likely your computer uses binary floating point,
and that means all small multiples of powers of two will stay unchanged,
for example 0.5.
Seems that on your computer, 0.7 and 0.9 get rounded down, everything
else except 0.5 gets rounded up, and 0.5 stays unchanged. (Is it a big
coincidence that only 2 values get rounded down and six get rounded up?
No, because 0.1, 0.2, 0.4 and 0.8 must behave the same on a computer
using binary floating point, and so must 0.3 and 0.6, because there is
factor of 2 between them).