如何确定一组值的标准偏差(stddev)?

时间:2009-05-22 00:26:54

标签: c# math statistics numerical

我需要知道一组数字与一组数字相比是否超出平均值的1 stddev等。

12 个答案:

答案 0 :(得分:99)

虽然平方和算法在大多数情况下都能正常工作,但是如果处理非常大的数字会导致大麻烦。你基本上可能会出现负差异......

另外,永远不要永远计算^ 2作为pow(a,2),a * a几乎肯定会更快。

到目前为止,计算标准差的最佳方法是Welford's method。我的C非常生疏,但看起来像是:

public static double StandardDeviation(List<double> valueList)
{
    double M = 0.0;
    double S = 0.0;
    int k = 1;
    foreach (double value in valueList) 
    {
        double tmpM = M;
        M += (value - tmpM) / k;
        S += (value - tmpM) * (value - M);
        k++;
    }
    return Math.Sqrt(S / (k-2));
}

如果您拥有整个人口(而不是示例人口),请使用return Math.Sqrt(S / (k-1));

编辑:我根据Jason的评论更新了代码......

编辑:我还根据Alex的评论更新了代码......

答案 1 :(得分:7)

比Jaime的

快10倍解决方案,但要注意, 正如杰米所指出的那样:

  

&#34;虽然平方和算法在大多数情况下工作正常,但它   如果您正在处理非常大的数字,可能会造成大麻烦。您   基本上可能会出现负差异&#34;

如果你认为你正在处理非常大的数字或非常大量的数字,你应该使用这两种方法计算,如果结果相同,你肯定知道你可以使用&#34;我的&#34;你的方法。

    public static double StandardDeviation(double[] data)
    {
        double stdDev = 0;
        double sumAll = 0;
        double sumAllQ = 0;

        //Sum of x and sum of x²
        for (int i = 0; i < data.Length; i++)
        {
            double x = data[i];
            sumAll += x;
            sumAllQ += x * x;
        }

        //Mean (not used here)
        //double mean = 0;
        //mean = sumAll / (double)data.Length;

        //Standard deviation
        stdDev = System.Math.Sqrt(
            (sumAllQ -
            (sumAll * sumAll) / data.Length) *
            (1.0d / (data.Length - 1))
            );

        return stdDev;
    }

答案 2 :(得分:4)

Math.NET库为您提供了这个功能。

  

PM&GT;安装包MathNet.Numerics

var populationStdDev = new List<double>(1d, 2d, 3d, 4d, 5d).PopulationStandardDeviation();

var sampleStdDev = new List<double>(2d, 3d, 4d).StandardDeviation();

有关详细信息,请参阅http://numerics.mathdotnet.com/docs/DescriptiveStatistics.html

答案 3 :(得分:3)

Jaime接受的答案很棒,除非您需要在最后一行中除以k-2(您需要除以“number_of_elements-1”)。 更好的是,从0开始k:

public static double StandardDeviation(List<double> valueList)
{
    double M = 0.0;
    double S = 0.0;
    int k = 0;
    foreach (double value in valueList) 
    {
        k++;
        double tmpM = M;
        M += (value - tmpM) / k;
        S += (value - tmpM) * (value - M);
    }
    return Math.Sqrt(S / (k-1));
}

答案 4 :(得分:2)

代码段:

public static double StandardDeviation(List<double> valueList)
{
    if (valueList.Count < 2) return 0.0;
    double sumOfSquares = 0.0;
    double average = valueList.Average(); //.NET 3.0
    foreach (double value in valueList) 
    {
        sumOfSquares += Math.Pow((value - average), 2);
    }
    return Math.Sqrt(sumOfSquares / (valueList.Count - 1));
}

答案 5 :(得分:2)

您可以通过累积均值和均方

来避免对数据进行两次传递
cnt = 0
mean = 0
meansqr = 0
loop over array
    cnt++
    mean += value
    meansqr += value*value
mean /= cnt
meansqr /= cnt

并形成

sigma = sqrt(meansqr - mean^2)

因素cnt/(cnt-1)通常也是合适的。

BTW--对AverageDemi答案中数据的第一次传递隐藏在对{{1}}的调用中。这样的事情在一个小清单上肯定是微不足道的,但如果列表超过缓存的大小,甚至是工作集,那么这就是买卖协议。

答案 6 :(得分:1)

我发现Rob的有用答案与我使用excel看到的完全不一致。为了匹配excel,我将AverageList中的Average传递给StandardDeviation计算。

这是我的两分钱......显然你可以从函数里面的valueList计算移动平均线(ma) - 但是在我需要standardDeviation之前我就已经知道了。

public double StandardDeviation(List<double> valueList, double ma)
{
   double xMinusMovAvg = 0.0;
   double Sigma = 0.0;
   int k = valueList.Count;


  foreach (double value in valueList){
     xMinusMovAvg = value - ma;
     Sigma = Sigma + (xMinusMovAvg * xMinusMovAvg);
  }
  return Math.Sqrt(Sigma / (k - 1));
}       

答案 7 :(得分:1)

使用扩展方法。

using System;
using System.Collections.Generic;

namespace SampleApp
{
    internal class Program
    {
        private static void Main()
        {
            List<double> data = new List<double> {1, 2, 3, 4, 5, 6};

            double mean = data.Mean();
            double variance = data.Variance();
            double sd = data.StandardDeviation();

            Console.WriteLine("Mean: {0}, Variance: {1}, SD: {2}", mean, variance, sd);
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    }

    public static class MyListExtensions
    {
        public static double Mean(this List<double> values)
        {
            return values.Count == 0 ? 0 : values.Mean(0, values.Count);
        }

        public static double Mean(this List<double> values, int start, int end)
        {
            double s = 0;

            for (int i = start; i < end; i++)
            {
                s += values[i];
            }

            return s / (end - start);
        }

        public static double Variance(this List<double> values)
        {
            return values.Variance(values.Mean(), 0, values.Count);
        }

        public static double Variance(this List<double> values, double mean)
        {
            return values.Variance(mean, 0, values.Count);
        }

        public static double Variance(this List<double> values, double mean, int start, int end)
        {
            double variance = 0;

            for (int i = start; i < end; i++)
            {
                variance += Math.Pow((values[i] - mean), 2);
            }

            int n = end - start;
            if (start > 0) n -= 1;

            return variance / (n);
        }

        public static double StandardDeviation(this List<double> values)
        {
            return values.Count == 0 ? 0 : values.StandardDeviation(0, values.Count);
        }

        public static double StandardDeviation(this List<double> values, int start, int end)
        {
            double mean = values.Mean(start, end);
            double variance = values.Variance(mean, start, end);

            return Math.Sqrt(variance);
        }
    }
}

答案 8 :(得分:0)

/// <summary>
/// Calculates standard deviation, same as MATLAB std(X,0) function
/// <seealso cref="http://www.mathworks.co.uk/help/techdoc/ref/std.html"/>
/// </summary>
/// <param name="values">enumumerable data</param>
/// <returns>Standard deviation</returns>
public static double GetStandardDeviation(this IEnumerable<double> values)
{
    //validation
    if (values == null)
        throw new ArgumentNullException();

    int lenght = values.Count();

    //saves from devision by 0
    if (lenght == 0 || lenght == 1)
        return 0;

    double sum = 0.0, sum2 = 0.0;

    for (int i = 0; i < lenght; i++)
    {
        double item = values.ElementAt(i);
        sum += item;
        sum2 += item * item;
    }

    return Math.Sqrt((sum2 - sum * sum / lenght) / (lenght - 1));
}

答案 9 :(得分:0)

这是人口标准差

private double calculateStdDev(List<double> values)
{
    double average = values.Average();
    return Math.Sqrt((values.Select(val => (val - average) * (val - average)).Sum()) / values.Count);
}

对于样本标准偏差,只需在上述代码中将[values.Count]更改为[values.Count -1]。

确保您的集合中没有只有1个数据点。

答案 10 :(得分:0)

我们也许可以在Python中使用统计信息模块。它具有stedev()和pstdev()命令,分别计算样本和总体的标准偏差。

详细信息:https://www.geeksforgeeks.org/python-statistics-stdev/

将统计信息导入为st print(st.ptdev(dataframe ['column name']))

答案 11 :(得分:0)

所有其他答案的问题在于他们认为你拥有自己的答案 大数据中的数据。如果你的数据是即时进入的,那就是 更好的方法。无论您如何存储数据,此类都有效。它还为您提供Waldorf方法或平方和方法的选择。两种方法都使用单次传递。

public final class StatMeasure {
  private StatMeasure() {}

  public interface Stats1D {

    /** Add a value to the population */
    void addValue(double value);

    /** Get the mean of all the added values */
    double getMean();

    /** Get the standard deviation from a sample of the population. */
    double getStDevSample();

    /** Gets the standard deviation for the entire population. */
    double getStDevPopulation();
  }

  private static class WaldorfPopulation implements Stats1D {
    private double mean = 0.0;
    private double sSum = 0.0;
    private int count = 0;

    @Override
    public void addValue(double value) {
      double tmpMean = mean;
      double delta = value - tmpMean;
      mean += delta / ++count;
      sSum += delta * (value - mean);
    }

    @Override
    public double getMean() { return mean; }

    @Override
    public double getStDevSample() { return Math.sqrt(sSum / (count - 1)); }

    @Override
    public double getStDevPopulation() { return Math.sqrt(sSum / (count)); }
  }

  private static class StandardPopulation implements Stats1D {
    private double sum = 0.0;
    private double sumOfSquares = 0.0;
    private int count = 0;

    @Override
    public void addValue(double value) {
      sum += value;
      sumOfSquares += value * value;
      count++;
    }

    @Override
    public double getMean() { return sum / count; }

    @Override
    public double getStDevSample() {
      return (float) Math.sqrt((sumOfSquares - ((sum * sum) / count)) / (count - 1));
    }

    @Override
    public double getStDevPopulation() {
      return (float) Math.sqrt((sumOfSquares - ((sum * sum) / count)) / count);
    }
  }

  /**
   * Returns a way to measure a population of data using Waldorf's method.
   * This method is better if your population or values are so large that
   * the sum of x-squared may overflow. It's also probably faster if you
   * need to recalculate the mean and standard deviation continuously,
   * for example, if you are continually updating a graphic of the data as
   * it flows in.
   *
   * @return A Stats1D object that uses Waldorf's method.
   */
  public static Stats1D getWaldorfStats() { return new WaldorfPopulation(); }

  /**
   * Return a way to measure the population of data using the sum-of-squares
   * method. This is probably faster than Waldorf's method, but runs the
   * risk of data overflow.
   *
   * @return A Stats1D object that uses the sum-of-squares method
   */
  public static Stats1D getSumOfSquaresStats() { return new StandardPopulation(); }
}