See You at TechEd

I’ll Be at TechEd North America in Houston next week (12-15 May, 2014).  If you’re a fan of the 2,000 Things blogs and will be in Houston, look me up.  (E.g. DM @spsexton on Twitter).  We can go grab a beer and sing the praises of C#, WPF and all things .NET.

Advertisements

#1,092 – Positive and Negative Zero

Because .NET uses the IEEE 754 standard to represent floating point numbers, it allows representing both positive and negative zero values.  (+0.0 and -0.0).

Mathematically, +0.0 is equal to -0.0 and an equality check in C# will return a true result.  However, although the values are considered equal, either value can be represented in C# and they are stored differently in memory.

            float zero = 0.0f;
            float negZero = -0.0f;

            bool theyAreEqual = zero == negZero;   // true

            // 00-00-00-00
            Console.WriteLine(BitConverter.ToString(BitConverter.GetBytes(zero)));

            // 00-00-00-80
            Console.WriteLine(BitConverter.ToString(BitConverter.GetBytes(negZero)));

            float sum1 = zero + 1.0f;
            float sum2 = negZero + 1.0f;
            bool sumsEqual = sum1 == sum2;    // true

1092-001

 

You can think of  a floating point representation of zero as being either zero or a very small positive number that rounds to zero when stored as a floating point.  If the value was a tiny bit above zero before rounding, it’s stored as +0.0.  If it was a bit below zero before rounding, it’s stored as -0.0.