【问题标题】:Generate dynamic equation based on Dictionary input根据字典输入生成动态方程
【发布时间】:2017-03-16 10:32:50
【问题描述】:

我想创建一个 C# 方法,该方法接受包含已知值和查询值的字典对象(例如,<int, double> 类型),以便可以从字典和查询值生成方程式被查找返回一个插值。

作为模拟:

public double ReturnValue(Dictionary<int, double>, int queryValue)
{
   // Generates an equation (e.g. in the form of y = mx + c) based on the dictionary object values
   // Looks up y based on queryValue as an input in the variable x

   return y;
}

Creating dynamic formula - 这看起来像是我想要的,但对于我的情况来说似乎有点太复杂了。

感谢您的任何建议 - 谢谢。

更新:一个字典对象的例子:

var temperatureDic = new Dictionary<int, double>()
{
    { 0, 1.10},
    { 5, 1.06},
    { 10, 1.03 },
    { 15, 1.00 },
    { 20, 0.97 },
    { 25, 0.93 },
    { 30, 0.89 },
    { 35, 0.86 },
    { 40, 0.82 },
    { 45, 0.77 }
};

【问题讨论】:

    标签: c# dictionary


    【解决方案1】:

    根据您对y = ax + b 的要求,我假设您正在寻找一个简单的线性回归? (wikipedia)

    如果是这样,this simple formula should suffice。适应您的Dictionary 要求:

    void Main()
    {
        var  temperatureDic = new Dictionary<int, double>()
        {
            { 0, 1.10},{ 5, 1.06},{ 10, 1.03 },{ 15, 1.00 },{ 20, 0.97 },
            { 25, 0.93 },{ 30, 0.89 },{ 35, 0.86 },{ 40, 0.82 },{ 45, 0.77 }
        };
    
        Debug.WriteLine(ReturnValue(temperatureDic, 8)); // 1.0461
    }
    
    public double ReturnValue(Dictionary<int, double> dict, int queryValue)
    {
        // Assuming dictionary Keys are x and Values are y
        var N = dict.Count;
        var sx = dict.Keys.Sum();
        var sxx = dict.Keys.Select(k => k*k).Sum();
        var sy = dict.Values.Sum();
        var sxy = dict.Select(item => item.Key * item.Value).Sum();
    
        var a = (N * sxy - sx * sy) / (N * sxx - sx * sx);
        var b = (sy - a * sx) / N;
    
        Debug.WriteLine($"a={a}, b={b}"); 
    
        // Now that we have a & b, we can calculate y = ax + b
        return a * queryValue + b;
    }
    

    这会给你a=-0.007115b=1.10309which is confirmed by WolframAlpha

    现在,如果你想要quadratic, cubic, or quartic formulas,那你的日子会更难过..

    【讨论】:

      猜你喜欢
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 2013-10-04
      • 1970-01-01
      • 2020-02-22
      • 1970-01-01
      • 2022-10-21
      • 2020-12-13
      相关资源
      最近更新 更多