Skip to content

Instantly share code, notes, and snippets.

@AdnanCutura
Created September 16, 2019 23:34
Show Gist options
  • Save AdnanCutura/478c27879d660b9150c0048eba823e81 to your computer and use it in GitHub Desktop.
Save AdnanCutura/478c27879d660b9150c0048eba823e81 to your computer and use it in GitHub Desktop.
Linear interpolation in C#

Calculating linear interpolation in C#

Calculates, or predicts, a future value by using existing values.

using System;
using System.Collections.Generic;
using System.Linq;
namespace LinearInterpolation
{
class Program
{
static void Main(string[] args)
{
// Input pairs in form of a key(x) - value(y)
var knownPairsXY = new SortedList<int, int>()
{
{0, 0},
{30, 35},
{70, 90 },
{100, 130}
};
// Input keys(x) for predicting a value(y) pairs
var forecastKeys = new List<int> { 10, 20, 40, 50, 60, 80, 190 };
// Ensuring interpolation
if (forecastKeys.Max() >= knownPairsXY.Keys.Max())
throw new Exception("The maximum value of the forecast points must be lower!");
if (forecastKeys.Min() <= knownPairsXY.Keys.Min())
throw new Exception("The minimum value of the forecast points must be higher!");
var avgX = knownPairsXY.Keys.Average();
var avgY = knownPairsXY.Values.Average();
var level = SlopeLevel(knownPairsXY);
foreach (var forecastKey in forecastKeys)
{
// Calculating predicted value
var predictedValue = (avgY - level * avgX) + level * forecastKey;
knownPairsXY.Add(forecastKey, (int)Math.Round(predictedValue));
}
Console.WriteLine("\t-KEY-\t-VALUE-");
foreach (var (key, value) in knownPairsXY)
Console.WriteLine("\t{0}:\t{1}", key, value);
}
/// <summary>
/// Calculates the slope level for given values
/// </summary>
/// <param name="knownPairsXY"> The known x and y values </param>
/// <returns> Slope level </returns>
private static double SlopeLevel(SortedList<int, int> knownPairsXY)
{
var top = 0.0;
var bottom = 0.0;
var avgX = knownPairsXY.Keys.Average();
var avgY = knownPairsXY.Values.Average();
// Calculating top and bottom bound
for (var i = 0; i < knownPairsXY.Count; i++)
{
top += (knownPairsXY.Keys[i] - avgX) * (knownPairsXY.Values[i] - avgY);
bottom += Math.Pow((knownPairsXY.Keys[i] - avgX), 2);
}
return top / bottom;
}
}
}
@MohammadrezaMC2
Copy link

Hello and thank you for your code
I have a code in Matlab which uses interp1 function:
https://ch.mathworks.com/help/matlab/ref/interp1.html

I need the same function in C#, can you help with that?

@DavidHoldaway
Copy link

DavidHoldaway commented May 11, 2022

Hello and thank you for your code I have a code in Matlab which uses interp1 function: https://ch.mathworks.com/help/matlab/ref/interp1.html

I need the same function in C#, can you help with that?

I assume this is now very old but it shows up in google so this was my solution:

    public static double[] Interp(double[] x, double[] v, double[] xq)
    {
        var stepInterp = new MathNet.Numerics.Interpolation.StepInterpolation(x, v);
        return xq.Select(q => stepInterp.Interpolate(q)).ToArray();
    }

If you want something more complicated there is spline interpolation stuff there as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment