我需要计算一堆数值数据的平均值、标准差、中位数等。我可以使用一个好的开源 .NET 库吗?我找到了 NMath,但它不是免费的,可能对我的需求来说有点过分了。
8 回答
你必须要小心。如果浮点运算是完美的,有几种计算标准偏差的方法会给出相同的答案。对于某些数据集,它们都是准确的,但在某些情况下,有些比其他数据集要好得多。
我在这里看到的方法是最有可能给出错误答案的方法。我自己使用它,直到它撞到我身上。
请参阅比较计算标准差的三种方法。
我在 CodeProject 网站上找到了这个。它看起来像是一个很好的 C# 类,用于处理大多数基本统计函数。
看看MathNet 它不是专门用于统计的,但可能有你想要的有用功能
Apache Maths.Common 并通过IKVM运行它。
我决定自己写会更快,这正是我需要的。这是代码...
/// <summary>
/// Very basic statistical analysis routines
/// </summary>
public class Statistics
{
List<double> numbers;
public double Sum { get; private set; }
public double Min { get; private set; }
public double Max { get; private set; }
double sumOfSquares;
public Statistics()
{
numbers = new List<double>();
}
public int Count
{
get { return numbers.Count; }
}
public void Add(double number)
{
if(Count == 0)
{
Min = Max = number;
}
numbers.Add(number);
Sum += number;
sumOfSquares += number * number;
Min = Math.Min(Min,number);
Max = Math.Max(Max,number);
}
public double Average
{
get { return Sum / Count; }
}
public double StandardDeviation
{
get { return Math.Sqrt(sumOfSquares / Count - (Average * Average)); }
}
/// <summary>
/// A simplistic implementation of Median
/// Returns the middle number if there is an odd number of elements (correct)
/// Returns the number after the midpoint if there is an even number of elements
/// Sorts the list on every call, so should be optimised for performance if planning
/// to call lots of times
/// </summary>
public double Median
{
get
{
if (numbers.Count == 0)
throw new InvalidOperationException("Can't calculate the median with no data");
numbers.Sort();
int middleIndex = (Count) / 2;
return numbers[middleIndex];
}
}
}
AForge.NET有 AForge.Math 命名空间,提供一些基本的统计函数:Histogram、mean、median、stddev、entropy。
如果您只需要一次性处理数字,那么电子表格无疑是您最好的工具。从 C# 中吐出一个简单的 CSV 文件很简单,然后您可以将其加载到 Excel(或其他)中:
class Program
{
static void Main(string[] args)
{
using (StreamWriter sw = new StreamWriter("output.csv", false, Encoding.ASCII))
{
WriteCsvLine(sw, new List<string>() { "Name", "Length", "LastWrite" });
DirectoryInfo di = new DirectoryInfo(".");
foreach (FileInfo fi in di.GetFiles("*.mp3", SearchOption.AllDirectories))
{
List<string> columns = new List<string>();
columns.Add(fi.Name.Replace(",", "<comma>"));
columns.Add(fi.Length.ToString());
columns.Add(fi.LastWriteTime.Ticks.ToString());
WriteCsvLine(sw, columns);
}
}
}
static void WriteCsvLine(StreamWriter sw, List<string> columns)
{
sw.WriteLine(string.Join(",", columns.ToArray()));
}
}
然后,您可以“启动 excel output.csv”并使用“=MEDIAN(B:B)”、“=AVERAGE(B:B)”、“=STDEV(B:B)”等函数。你会得到图表、直方图(如果你安装了分析包)等。
以上并不能解决所有问题;通用 CSV 文件比您想象的要复杂。但对于我所做的大部分分析来说,它已经“足够好”了。