#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.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: