Skip to content

Instantly share code, notes, and snippets.

@CitizenInsane
Created August 24, 2012 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CitizenInsane/3449954 to your computer and use it in GitHub Desktop.
Save CitizenInsane/3449954 to your computer and use it in GitHub Desktop.
How to test for NaN with generics (or why NaN.Equals(NaN) == true) ?
namespace TestForNaNWithGenerics
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
[TestFixture]
class TestForNaN
{
[Test]
public void Tests()
{
var values = new[] { double.NaN, 42.0, 13.0, double.NaN, 666.0, double.NaN };
var min = genericFindMin(values);
var max = genericFindMax(values);
Assert.AreEqual(13.0, min);
Assert.AreEqual(666.0, max);
}
private bool isNaN<T>(T value) where T : IEquatable<T>
{
//var d = value as double?;
//if (d.HasValue) { return double.IsNaN(d.Value); }
return !value.Equals(value);
}
private bool notNaN<T>(T value) where T : IEquatable<T>
{
return !isNaN(value);
}
private T genericFindMin<T>(IEnumerable<T> values) where T: IComparable<T>, IEquatable<T>
{
// Test parameters
if ((values == null) || (!values.Any())) { throw new ArgumentException("No value provided"); }
// Remove NaNs
var noNaNs = values.Where(notNaN);
if (!noNaNs.Any()) { return values.First(isNaN); }
// Work without NaNs
var min = noNaNs.First();
foreach (var value in noNaNs)
{
if (value.CompareTo(min) < 0) { min = value; }
}
return min;
}
private T genericFindMax<T>(IEnumerable<T> values) where T : IComparable<T>, IEquatable<T>
{
// Test parameters
if ((values == null) || (!values.Any())) { throw new ArgumentException("No value provided"); }
// Remove NaNs
var noNaNs = values.Where(notNaN);
if (!noNaNs.Any()) { return values.First(isNaN); }
// Work without NaNs
var max = noNaNs.First();
foreach (var value in noNaNs)
{
if (value.CompareTo(max) > 0) { max = value; }
}
return max;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment