我想编写一个LinearInterpolator类,其中X是X轴值的类型,而Y是Y轴值的类型。我看不到如何做到这一点,以使X可以是DateTime或double。该类如下所示(未经测试):
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;
}
}
}
}
在C++中这很容易,但是我是C#泛型的新手,所以我们将不胜感激。
最佳答案
使用DateTime.Ticks
作为插值。您可以使用long
类型作为泛型来在时间之间进行插值。
关于c# - 通用线性插值器: how to cope with DateTime?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2366985/