简体   繁体   English

在C#中,应使用哪种数据类型存储具有标准偏差的数字列表?

[英]In C#, what data type should I use to store a list of numbers with standard deviation?

I'm performing some tests and I have a list of values with errors of the form: 我正在执行一些测试,并且有一个带有以下形式错误的值列表:

12.7 ± 0.3
14.2 ± 0.1
70.8 ± 0.5

I need to keep the standard deviation alongside the value, as I need to use it for various calculations later on. 我需要将标准偏差与值保持一致,因为稍后需要将其用于各种计算。

At the moment I'm just using 目前我只是在使用

List<KeyValuePair<double, double>>

But are there any better solution? 但是还有更好的解决方案吗?

If the values are not going to change I would go with struct. 如果值不改变,我将使用struct。 You can add logic (but you can do that with a class also). 您可以添加逻辑(但是您也可以使用一个类来实现)。 Go decimal unless you specifically need double. 除非您特别需要加倍,否则应十进制。

public struct StdDev
{
    public decimal Val { get; }
    public decimal Dev { get; }
    public decimal Max { get { return Val + Dev; } }
    public decimal Min { get { return Val - Dev; } }
    public bool IsInDev (decimal val)
    {
        return val >= Min && val <= Max;
    }
    public override string ToString()
    {
        return $"{Val} +- {Dev}";
    }
    public StdDev (decimal val, decimal dev)
    {
        Val = val;
        Dev = dev;
    }
}

You could override Equals and GetHashCode. 您可以覆盖Equals和GetHashCode。

Here are some other options to what you currently have: 以下是您目前拥有的其他一些选择:

It's up to you to choose and use what is convinient. 选择和使用方便的方法取决于您。 Don't know if performance is what you are looking for. 不知道性能是否就是您想要的。

Option 1 (if you are using C# 7.0 or later): 选项1(如果使用的是C#7.0或更高版本):

How about Tuples ? 元组怎么样?

You won't have key value pair in tuple but rather items. 元组中没有键值对,而是项。

Option 2: Like Dan wilson mentioned in the comment to your question make a class with value and error 选项2:就像对问题的评论中提到的Dan wilson一样,让类充满价值和错误

public class ValueWithDeviation
{
    public double Value {get; set;}

    public double Deviation {get; set;}
}

Then you could have IEnumerable<ValueWithError> 那么你可能有IEnumerable<ValueWithError>

As DanWilson and Cybercop suggest, I'd say that creating a dedicated type ( a class or a struct ) is the way to go, because the value with the deviation can be seen together as a logical object. 正如DanWilson和Cyber​​cop所建议的那样,我要说的是创建专用类型( 类或结构 ),因为带有偏差的值可以一起看作一个逻辑对象。 Also, that will make your life easier when you want to display the values, as you will just need to override the ToString method in your type. 另外,当您要显示值时,这将使您的生活更加轻松,因为您只需要覆盖类型中的ToString方法即可。

As for the underlying type, it might be more convenient for you to use decimal instead of double , but that depends on your specific project/needs. 对于基础类型, 使用十进制而不是double可能更方便,但这取决于您的特定项目/需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM