問題描述
我需要計算通用列表的標準偏差.我會嘗試包含我的代碼.它是一個包含數據的通用列表.數據主要是浮點數和整數.這是我的相關代碼,沒有詳細介紹:
I need to calculate the standard deviation of a generic list. I will try to include my code. Its a generic list with data in it. The data is mostly floats and ints. Here is my code that is relative to it without getting into to much detail:
namespace ValveTesterInterface
{
public class ValveDataResults
{
private List<ValveData> m_ValveResults;
public ValveDataResults()
{
if (m_ValveResults == null)
{
m_ValveResults = new List<ValveData>();
}
}
public void AddValveData(ValveData valve)
{
m_ValveResults.Add(valve);
}
這里是需要計算標準差的函數:
public float LatchStdev()
{
float sumOfSqrs = 0;
float meanValue = 0;
foreach (ValveData value in m_ValveResults)
{
meanValue += value.LatchTime;
}
meanValue = (meanValue / m_ValveResults.Count) * 0.02f;
for (int i = 0; i <= m_ValveResults.Count; i++)
{
sumOfSqrs += Math.Pow((m_ValveResults - meanValue), 2);
}
return Math.Sqrt(sumOfSqrs /(m_ValveResults.Count - 1));
}
}
}
忽略 LatchStdev() 函數內部的內容,因為我確定它不正確.這只是我計算 st dev 的拙劣嘗試.我知道如何處理雙打列表,但不知道如何處理通用數據列表.如果有人有這方面的經驗,請幫忙.
Ignore whats inside the LatchStdev() function because I'm sure its not right. Its just my poor attempt to calculate the st dev. I know how to do it of a list of doubles, however not of a list of generic data list. If someone had experience in this, please help.
推薦答案
本文應該可以幫助你.它創建了一個函數來計算一系列 double
值的偏差.您所要做的就是提供一系列適當的數據元素.
This article should help you. It creates a function that computes the deviation of a sequence of double
values. All you have to do is supply a sequence of appropriate data elements.
得到的函數是:
private double CalculateStandardDeviation(IEnumerable<double> values)
{
double standardDeviation = 0;
if (values.Any())
{
// Compute the average.
double avg = values.Average();
// Perform the Sum of (value-avg)_2_2.
double sum = values.Sum(d => Math.Pow(d - avg, 2));
// Put it all together.
standardDeviation = Math.Sqrt((sum) / (values.Count()-1));
}
return standardDeviation;
}
這很容易適應任何泛型類型,只要我們為正在計算的值提供一個選擇器.LINQ 非常適合這一點,Select
函數允許您從自定義類型的通用列表中投影出一個數值序列,用于計算標準偏差:
This is easy enough to adapt for any generic type, so long as we provide a selector for the value being computed. LINQ is great for that, the Select
funciton allows you to project from your generic list of custom types a sequence of numeric values for which to compute the standard deviation:
List<ValveData> list = ...
var result = list.Select( v => (double)v.SomeField )
.CalculateStdDev();
這篇關于通用列表的標準偏差?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!