在计算十进制标准偏差期间获取 OverflowException

Getting OverflowException during calculation of a decimal Standard Deviation

正在通过将值插入文本框来计算标准偏差。我有以下代码:

public decimal calcStd(List<int> ppValuesArray)
{
    double std = 0;
    if (ppValuesArray.Count() > 0)
    {
        double avg = ppValuesArray.Average();

        double sum = ppValuesArray.Sum(d => Math.Pow(d - avg, 2));

        std = Math.Sqrt((sum) / ppValuesArray.Count() - 1);
    }
    decimal stdDev = Convert.ToDecimal(std);
    return (decimal)stdDev;

}

问题是当我多次输入相同的值时系统崩溃了。例如1,1,1,1 会使它崩溃。

我遇到错误:

System.OverflowException: 'Value was either too large or too small for a Decimal.'

有什么想法吗?

假设你在样本标准偏差之后,你错过了除数 -1 中的括号,即

std = Math.Sqrt((sum) / (ppValuesArray.Count() - 1));

你得到溢出的原因是因为 decimal 不能表示双精度值 NaN,如果你尝试取平方根,它由 Math.Sqrt(double) 返回的负数。

此外,您将 List<int> 作为输入的原因是什么? decimaldouble 似乎限制较少,具体取决于您使用的数据类型,例如

 public static decimal calcStd(IEnumerable<double> ppValuesArray)

此外,鉴于尝试获取单个值的样本 StdDev 现在将产生 DivideByZero 异常,建议您将守卫更改为:

if (ppValuesArray.Count() > 1)