When is a number not a number?


Pop quiz. What would the following C# code do?

float x = 1;
float y = 0;
float result = x / y;
  1. Fail to compile.
  2. Throw an overflow exception.
  3. Print “Infinity”
  4. Cause the universe to explode.

Here’s the thing, the code prints the word “Infinity”. Dividing any floating point variable by zero gives a special result which is encoded into the floating point variable range as “Infinity”. Now what about this?

float y = 0;
float result = y / y;

This time we get the message “NaN”, which means “Not a Number”. Dividing zero by zero does not give a number as a result. There just isn’t a value for this quantity. The value is not as big as as infinity or as small as zero its just, well, not a number. You get the same non-result if you divide infinity by infinity.

The C# runtimes are based on .NET which uses an IEEE (Institute of Electrical Electronics Engineers) standard that contains representations for negative infinity, positive infinity and “not a number”. Calculations in a C# program will produce these results when given dodgy values to work on. This is very important. You might think if you do silly things with numbers in your program you are going to get an exception thrown. Like this would.

int i = 1;
int j = 0;
int Result = i / j;

Run this code and it throws a “Divide by Zero” exception when it tries to, er, divide by zero. But this does not happen with floating point calculations. This is probably because the range of values for the int type does not include one to represent “infinity”.

The bottom line here is that if you do sums involving floating point values you can’t expect exceptions to be thrown if the calculations go wrong. The good news is that you can use methods provided by the float type to test results of calculations:

if (float.IsNaN(fresult))
    Console.WriteLine("Welcome to the Twilight Zone");

This prints the enigmatic message if the value in fresult is not a number.