I would like to write a LinearInterpolator class, where X is the type of the value of the X axis and Y is the type of the value of the Y axis. I don’t see how to do this so that X can be a DateTime or double. The class is something like below (which has not been verified):
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
{
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];
Y y = yLeft + ((x - xLeft) / (xRight - xLeft)) * (yRight - yLeft);
return y;
}
}
}
}
That would be easy in C ++, but I'm new to C # generics, so any help would be appreciated.
user284793
source
share