views:

1000

answers:

4

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);
    }
}
+10  A: 

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

Michael
+1 Why, why do I see after hitting the Submit button that someone has posted the links? :P
dirkgently
+1 http://msdn.microsoft.com/en-us/library/b1e65aza(VS.71).aspx Michael is correct, C# float only has 7 digit precision, and 99.999999f has 8 digits.
James
This is not C# specific. A single-precision IEEE-754 float will only be 32-bits, which gives around 7 decimal digits of precision. If you want better than that, use a double.
Wedge
Doubles just push the problem out a few more bits. What you really want are quad doubles like those from the QD library (see http://crd.lbl.gov/~dhbailey/mpdist/). There's an arbitrary precision library there too.
RBerteig
+2  A: 

This really is a tricky question. I'm running this from Visual Studio and the console closes so quickly I can't read the output!

John Rasch
Sarcasm is sarcasm.
Jabe
I think it's irony.
Prankster
Nah its Irony.NET :) Gee, names aren't important any more are they..
rama-jka toti
+3  A: 

Not a direct answer, but may help to understand what is going on:What Every Computer Scientist Should Know About Floating-Point Arithmetic.

dirkgently
A: 

The main thing is that this isn't just .Net: it's a limitation of the underlying system most every language will use to represent a float in memory. The precision only goes so far.

You can also have some fun with relatively simple numbers, when you take into account that it's not even base ten. 0.1, for example, is a repeating decimal when represented in binary.

Joel Coehoorn