#77 – Special Floating Point Values

In C#, the float and double types can represent regular floating point values as well as a handful of special values:

  • Positive and negative zero
  • Positive and negative infinity
  • Not-a-Number value (NaN)

Floating point types can represent both positive and negative zero values.  In most cases, the two different zero values are indistinguishable.  When converting to string, both will result in “0”.  Internally, in memory, however, a negative zero will have its sign bit set.

 float f1 = 1.0f * 0.0f;    // Positive zero - 0x00000000
 float f2 = -1.0f * 0.0f;   // Negative zero - 0x00000080  (sign bit set)

Negative and positive values for infinity are also part of the IEEE spec for floating-point arithmetic.

 float f1 = 1.0f / 0.0f;    // Infinity  - 0x0000807F
 float f2 = -1.0f / 0.0f;   // -Infinity - 0x000080FF

The Not-a-Number (NaN) value indicates an unrepresentable number.

 float f1 = 0.0f / 0.0f;        // NaN - 0x0000C0FF
 double d1 = Math.Sqrt(-1.0);   // NaN - 0x000000000000F8FF
Advertisements

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

One Response to #77 – Special Floating Point Values

  1. kai zhou says:

    Nice work, although this piece of knowledge is seldom used in my development work.
    Thanks Sean.

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 )

Google+ photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: