2017-03-16 38 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,那麼你會有一個更難的時間..