Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is floating point arithmetic in C# imprecise?

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
like image 555
Prankster Avatar asked Apr 15 '09 22:04

Prankster


1 Answers

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

like image 110
Michael Avatar answered Sep 18 '22 18:09

Michael