C# 基于字典输入生成动力学方程

C# 基于字典输入生成动力学方程,c#,dictionary,C#,Dictionary,我想创建一个C#方法,它接受一个dictionary对象(比如类型为),该对象包含已知值和一个查询值,这样就可以从dictionary生成一个等式,并查找查询值以返回一个插值 作为模拟: public double ReturnValue(Dictionary<int, double>, int queryValue) { // Generates an equation (e.g. in the form of y = mx + c) based on the diction

我想创建一个C#方法,它接受一个dictionary对象(比如类型为
),该对象包含已知值和一个查询值,这样就可以从dictionary生成一个等式,并查找查询值以返回一个插值

作为模拟:

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;
}
public双返回值(Dictionary,int queryValue)
{
//根据字典对象值生成一个方程式(例如,以y=mx+c的形式)
//基于查询值查找y作为变量x中的输入
返回y;
}
-这看起来像是我想要的,但对我的案子来说似乎有点太复杂了

谢谢你的建议

更新:字典对象示例:

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 }
};
var temperatureedic=new Dictionary()
{
{ 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 }
};

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

如果是的话。适合您的
词典
要求:

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;
}
void Main()
{
var temperatureDic=新字典()
{
{ 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(返回值(temperatureDic,8));//1.0461
}
公共双返回值(Dictionary dict,int queryValue)
{
//假设字典键为x,值为y
var N=记录计数;
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();
变量a=(N*sxy-sx*sy)/(N*sxx-sx*sx);
var b=(sy-a*sx)/N;
WriteLine($“a={a},b={b}”);
//现在我们有了a和b,我们可以计算y=ax+b
返回a*查询值+b;
}
这将为您提供
a=-0.007115
b=1.10309

现在,如果你愿意,你会有一个更艰难的时间