Skip to content

Instantly share code, notes, and snippets.

@13xforever
Last active Mar 25, 2021
Embed
What would you like to do?
Some statistics functions
using System;
using System.Collections.Generic;
using System.Numerics;
namespace Math.Statistics
{
public static class Statistics
{
public static long Mean(this IEnumerable<long> data)
{
if (data == null) throw new ArgumentNullException("data");
BigInteger sum = 0;
int itemCount = 0;
foreach (var value in data)
{
sum += value;
itemCount ++;
}
if (itemCount == 0) throw new ArgumentException("data");
return (long)(sum / itemCount);
}
public static double StdDev(this IEnumerable<long> data)
{
if (data == null) throw new ArgumentNullException("data");
BigInteger σx = 0, σx2 = 0;
int n = 0;
foreach (var value in data)
{
σx += value;
σx2 += (BigInteger)value * value;
n++;
}
if (n == 0) throw new ArgumentException("data");
BigInteger σ2 = σx * σx;
return System.Math.Sqrt((double)((n * σx2) - σ2) / ((n - 1) * n));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment