Skip to content

Instantly share code, notes, and snippets.

@tcshao
Last active October 11, 2015 09:48
Show Gist options
  • Save tcshao/3840562 to your computer and use it in GitHub Desktop.
Save tcshao/3840562 to your computer and use it in GitHub Desktop.
feeding a dynamic interpolation function to a series
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Numerical
{
public class DataSeries
{
public List<double> X { get; set; }
public List<double> Y { get; set; }
public Func<double, double, double, double, double, double> Interpolator { get; set; }
public int Length
{
get { return X.Count; }
}
public double XMax
{
get { return X[Length - 1]; }
}
public double XMin
{
get { return X[0]; }
}
public DataSeries()
{
X = new List<double>();
Y = new List<double>();
Interpolator = StandardInterpolator;
}
public void Add(double x, double y)
{
if (X.Count == 0 || x > XMax)
{
// No previous items in the list or the current x is larger than
// what is already in the list
X.Add(x);
Y.Add(y);
}
else
{
// Instead of adding to the end, the current x needs to be inserted
// at an intermediate row to keep a sequential X.
for (int rowIndex = 0; rowIndex < Length; rowIndex++)
{
if (x < X[rowIndex])
{
X.Insert(rowIndex, x);
Y.Insert(rowIndex, y);
break;
}
}
}
}
public double GetValue(double x)
{
if (x < XMin || x > XMax) return 0;
int i = 0;
var searchResult = Array.BinarySearch(X.ToArray(), x);
if(searchResult < 0)
{
i = ~searchResult - 1;
return Interpolator(X[i], X[i + 1], Y[i], Y[i + 1], x);
}
else
{
return Y[i];
}
}
public double StandardInterpolator(double x1, double x2, double y1, double y2, double value)
{
double A = (x2 - value) / (x2 - x1);
double B = 1 - A;
return A * y1 + B * y2;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment