基于字典输入生成动态方程

时间:2017-03-16 01:01:50

标签: c# dictionary

我想创建一个C#方法,接受包含已知值和查询值的字典对象(例如,类型为with open("CombinedList.txt", "w") as f: for line in New_list: f.write(line + "\n") print('File Successfully written.') ),以便可以从字典和字典生成方程查询查询值以返回插值。

作为模拟:

<int, double>

Creating dynamic formula - 这看起来像我正在追求的,但对我来说似乎有点太复杂。

感谢任何建议 - 谢谢。

更新:字典对象的示例:

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;
}

1 个答案:

答案 0 :(得分:0)

根据您对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,那么你将会有更难的时间..