not a number (NaN)
System.Double.NaN represents the result of an invalid or undefined calculation.
The code below demonstrates a number of ways to generate NaN, and how it is important
to determine if a number is NaN using the function System.Double.IsNaN() rather
than checking for equality.
When writing numerical code, it is important to check all eventualities of every
calculation. For example, every time a division is performed, is it possible that
the code might divide 0.0 by 0.0? An exception would not be raised, but the result
would be invalid.
Although out of scope of this article, it should be mentioned that there are actually
two types of NaN. The first is called a signalling NaN (SNaN or 1.#INF) denoting
that the operation was invalid, and the second is a quiet NaN (QNaN or –1.#IND),
denoting that the operation is undefined.
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace NumericalCodeTips
{
[TestClass]
public class NaNTest
{
[TestMethod]
public void NaN()
{
Assert.IsTrue(double.IsNaN(double.NaN));
Assert.IsTrue(double.IsNaN(0.0 / 0.0));
Assert.IsTrue(double.IsNaN(Math.Sqrt(-1.0)));
Assert.IsTrue(double.IsNaN(double.PositiveInfinity / double.PositiveInfinity));
Assert.IsTrue(double.IsNaN(double.PositiveInfinity - double.PositiveInfinity));
}
[TestMethod]
public void NaNEquality()
{
double x = (0.0 / 0.0);
Assert.IsFalse(x == Double.NaN);
Assert.IsTrue(double.IsNaN(x));
}
}
}