Alex Rivera | Logout

Why is floating point arithmetic in C# imprecise?

Asked 2009-04-15T22:12:57.763
19

Why does the following program print what it prints?

class Program
{
    static void Main(string[] args)
    {
        float f1 = 0.09f*100f;
        float f2 = 0.09f*99.999999f;

        Console.WriteLine(f1 > f2);
    }
}

Output is

false
Edit
Report

1 Answer

43

Floating point only has so many digits of precision. If you're seeing f1 == f2, it is because any difference requires more precision than a 32-bit float can represent.

I recommend reading What Every Computer Scientist Should Read About Floating Point

answered 2009-04-15T22:15:55.200

Your Answer