I'd like to write a LinearInterpolator class, where X is the type of the X axis value, and Y the type of the Y axis value. I can't see how to do this such that X could be a DateTime or a double. The class is something like below (which is untested):
class LinearInterpolator<X, Y>
{
private List<X> m_xAxis;
private List<Y> m_yAxis;
public LinearInterpolator(List<X> x, List<Y> y)
{
m_xAxis = x;
m_yAxis = y;
}
public Y interpolate(X x)
{
int i = m_xAxis.BinarySearch(x);
if (i >= 0)
{
return m_yAxis[i];
}
else
{
// Must interpolate.
int rightIdx = ~i;
if (rightIdx >= m_xAxis.Count)
--rightIdx;
int leftIdx = rightIdx - 1;
X xRight = m_xAxis[rightIdx];
X xLeft = m_xAxis[leftIdx];
Y yRight = m_yAxis[rightIdx];
Y yLeft = m_yAxis[leftIdx];
// This is the expression I'd like to write generically.
// I'd also like X to be compilable as a DateTime.
Y y = yLeft + ((x - xLeft) / (xRight - xLeft)) * (yRight - yLeft);
return y;
}
}
}
}
It'd be easy in C++, but I'm new to C# generics so any help would be appreciated.