通用列表的标准偏差?
- 作者: 做人应努力
- 来源: 51数据库
- 2023-02-13
问题描述
我需要计算通用列表的标准偏差.我会尝试包含我的代码.它是一个包含数据的通用列表.数据主要是浮点数和整数.这是我的相关代码,没有详细介绍:
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();
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源