gpt4 book ai didi

c# - 如何修复 StdDev 计算中的浮点伪像?

转载 作者:太空宇宙 更新时间:2023-11-03 15:41:54 24 4
gpt4 key购买 nike

我试图用下一个方法计算标准差:

private static double? StdDev(IReadOnlyCollection<double> items) {
if(items == null) {
throw new ArgumentNullException("items");
}//if

var count = items.Count;
if(count == 0 || count == 1) {
return null;
}//if

var sum = 0d;
var sqrsum = 0d;
foreach(var item in items) {
sum += item;
sqrsum += item * item;
}//for

var average = sum / count;
var stddev = Math.Sqrt((sqrsum - count * average * average) / (count - 1));
return stddev;
}

有时,表达式“sqrsum - count * average * average”小于 0,Math.Sqrt 返回 NaN。例如,在这种情况下:

private static void Main() {
var data = Enumerable.Repeat(86.399999999999991, 3).ToList();
var stddev = StdDev(data);
Console.WriteLine("StdDev = " + stddev);
}

如何在我的代码中修复这种情况?我应该使用 Math.Abs​​(sqrsum - count * average * average) 还是应该四舍五入?

最佳答案

我认为以下代码可以帮助您计算标准偏差。

    private object StdDev(IReadOnlyCollection<double> items)
{
if (items == null)
{
throw new ArgumentNullException("items");
}//if

var count = items.Count;
if (count == 0 || count == 1)
{
return null;
}//if

var sum = 0d;
var sqrsum = 0d;
foreach (var item in items)
{
sum += item;
sqrsum += item * item;
}//for

var average = sum / count;

double deviation = 0d;
for (int i = 0; i < items.Count(); i++)
{
deviation += (items[i] - average) * (items[i] - average);
}
deviation = deviation / (count - 1);

var stddev = Math.Sqrt(deviation);
return stddev;
}

关于c# - 如何修复 StdDev 计算中的浮点伪像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29963273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com