2

I wrote a program in c#

        static void Main(string[] args)
    {
        float   c = 1.111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111F;
        double  d = 1.111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111F;
        Console.WriteLine(d);
        Console.WriteLine(c);

        Console.WriteLine(c == d);
        Console.Read();
    }

output is:

1.11111116409302
1.111111
True

So,Question:
why is its output is true
Please help me understand this,Thanks!

  • 2
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – user703016 Dec 20 '13 at 04:40
  • c is the float approximation to the decimal number. d is the conversion to double of that float. As part of the comparison, c is converted to double. You are comparing the double conversion of the float approximation to a particular decimal number to itself, so of course the result is true. – Patricia Shanahan Dec 21 '13 at 04:34

1 Answers1

3

When you do the first assignment, the constant is truncated to fit the float. When you do the second assignment, the float-precision literal 1.1111...11F is converted to double. Since c contains the value of the 1.1111...11F literal, initialization of d is equivalent to

double d = ((double)c);

Both assignments change the precision of the constant from the literal, but they change it differently. That is why you see different printouts in the first two WriteLines.

When you compare c and d, the value with the lower precision, i.e. c, is converted to the type with the higher precision, i.e. to double. That is the same conversion as the conversion that has been performed when you assigned the 1.1111...11F literal to variable d, so the values compare the same in the == operation. In other words, when you do this

Console.WriteLine(c == d);

the compiler does this:

Console.WriteLine(((double)c) == d);

That is why the comparison returns true.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523