A Question about floating point represanation

Discussion in 'C Programming' started by Ketan Parikh, Aug 25, 2003.

1. Ketan ParikhGuest

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".

I would be very thankfull to u.

Have a nice time

Jay Hind.

Ketan Parikh, Aug 25, 2003

2. Jirka KlaueGuest

Ketan Parikh wrote:
....
> float k=0.7;
> if (k < 0.7)
> printf("Hey");
> else
> printf("Hello");
> }
>
> the o/p of the program is: "Hello" why?

See http://www.eskimo.com/~scs/C-faq/s14.html,
especially questions 14.1 and 14.5.

Jirka

Jirka Klaue, Aug 25, 2003

3. Christian BauGuest

In article <>,
(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".
>

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).

Christian Bau, Aug 25, 2003

k<0.7 is wrong. k =0.7 )

(Ketan Parikh) wrote in message news:<>...
> 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".
>