2

I would like to create a C# method that accepts a dictionary object (say, of type <int, double>) that contains known values and a query value in such a way that an equation can be generated from the dictionary and the query value is looked up to return an interpolated value.

As a mock:

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 - This looks like what I am aftering, but it seems a bit too complicated for my case.

Any advice is appreciated - thank you.

Update: An example of a dictionary object:

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 }
};
Community
  • 1
  • 1
taylorswiftfan
  • 1,371
  • 21
  • 35

1 Answers1

0

Based on your requirement of y = ax + b, I'm assuming you are looking for a simple Linear Regression? (wikipedia)

If so, this simple formula should suffice. Adapted to your Dictionary requirements:

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

This gives you a=-0.007115 and b=1.10309, which is confirmed by WolframAlpha.

Now, if you want quadratic, cubic, or quartic formulas, then you're gonna have a much harder time..

NPras
  • 3,135
  • 15
  • 29