diff --git a/src/Numerics/Statistics/Statistics.cs b/src/Numerics/Statistics/Statistics.cs
index dd2d3baf..9a957609 100644
--- a/src/Numerics/Statistics/Statistics.cs
+++ b/src/Numerics/Statistics/Statistics.cs
@@ -88,7 +88,7 @@ namespace MathNet.Numerics.Statistics
}
///
- /// Calculates the unbiased population variance estimator (on a dataset of size N will use an N-1 normalizer).
+ /// Calculates the unbiased population (sample) variance estimator (on a dataset of size N will use an N-1 normalizer).
///
/// The data to calculate the variance of.
/// The unbiased population variance of the sample.
@@ -121,11 +121,11 @@ namespace MathNet.Numerics.Statistics
}
}
- return variance / (j - 1);
+ return j > 1 ? variance/(j - 1) : double.NaN;
}
///
- /// Computes the unbiased population variance estimator (on a dataset of size N will use an N-1 normalizer) for nullable data.
+ /// Computes the unbiased population (sample) variance estimator (on a dataset of size N will use an N-1 normalizer) for nullable data.
///
/// The data to calculate the variance of.
/// The population variance of the sample.
@@ -171,7 +171,7 @@ namespace MathNet.Numerics.Statistics
}
}
- return variance / (j - 1);
+ return j > 1 ? variance/(j - 1) : double.NaN;
}
///
diff --git a/src/UnitTests/StatisticsTests/StatisticsTests.cs b/src/UnitTests/StatisticsTests/StatisticsTests.cs
index 1b6f51cf..a7bb8170 100644
--- a/src/UnitTests/StatisticsTests/StatisticsTests.cs
+++ b/src/UnitTests/StatisticsTests/StatisticsTests.cs
@@ -227,6 +227,22 @@ namespace MathNet.Numerics.UnitTests.StatisticsTests
AssertHelpers.AlmostEqual(2d, Statistics.StandardDeviation(gaussian.Samples().Take(10000)), 2);
}
+ [Test]
+ public void SampleVarianceOfEmptyAndSingleMustBeNaN()
+ {
+ Assert.That(Statistics.Variance(new double[0]), Is.NaN);
+ Assert.That(Statistics.Variance(new[] { 2d }), Is.NaN);
+ Assert.That(Statistics.Variance(new[] { 2d, 3d }), Is.Not.NaN);
+ }
+
+ [Test]
+ public void PopulationVarianceOfEmptyMustBeNaN()
+ {
+ Assert.That(Statistics.PopulationVariance(new double[0]), Is.NaN);
+ Assert.That(Statistics.PopulationVariance(new[] { 2d }), Is.Not.NaN);
+ Assert.That(Statistics.PopulationVariance(new[] { 2d, 3d }), Is.Not.NaN);
+ }
+
///
/// URL http://mathnetnumerics.codeplex.com/workitem/5667
///