2017-03-16 41 views
2

我想创建接受(<int, double>类型的发言权,)一个字典对象一个C#方法包含已知的值,并在这样的方式的查询值,该值的方程可以从生成字典并查询查询值以返回插值。生成动态方程基于字典输入

作为模拟:

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 - 这看起来像什么,我aftering,但似乎我的情况有点太复杂了。

任何建议表示赞赏 - 谢谢你。

更新:字典对象的例子:根据您的要求y = ax + b

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

回答

0

,我假设你正在寻找一个简单的线性回归? (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,那么你会有一个更难的时间..