Skip to content

Instantly share code, notes, and snippets.

@michaellperry
Created February 22, 2011 20:39
Show Gist options
  • Save michaellperry/839343 to your computer and use it in GitHub Desktop.
Save michaellperry/839343 to your computer and use it in GitHub Desktop.
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace StatisticalLinq
{
[TestClass]
public class VarianceTest
{
[TestMethod]
public void VarianceOf10Numbers()
{
var result = Enumerable.Range(1, 10)
.Select(i => (decimal)i) // Cast
.Select(i => new // Map
{
N2 = i*i,
N1 = i,
N0 = 1
})
.Aggregate((a1, a2) => new // Reduce
{
N2 = a1.N2 + a2.N2,
N1 = a1.N1 + a2.N1,
N0 = a1.N0 + a2.N0
});
decimal mean = result.N1 / result.N0;
decimal variance = (result.N2 - result.N1 * mean) / result.N0;
Assert.AreEqual(5.5m, mean);
Assert.AreEqual(8.25m, variance);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment