我的任务是创建一个计算线性插值的方法,其中Y是DateTime值,X是整数值。例如,查看以下值,如何查找7,8和9的值?
Date: Value:
05/01/2013 5
06/01/2013 7
10/01/2013 9
11/01/2013 1
15/01/2013 7
17/01/2013 2
02/02/2013 8
EDIT:
int interpMethod(DateTime x0, int y0, DateTime x1, int y1, int x)
{
return y0 * (x - x1) / (x0 - x1) + y1 * (x - x0) / (x1 - x0);
}
答案 0 :(得分:3)
为了在2个其他点之间插入点,您需要计算变化率,然后将其应用于2点之间的距离。
此外,请确保您的数据类型保持一致。您显示的数据有两倍,但您的方法只处理整数。另外,你在问题中要求输入一个double并找到DateTime,但是你要返回一个整数?
public static DateTime Interpolate(DateTime x0, double y0, DateTime x1, double y1, double target)
{
//this will be your seconds per y
double rate = (x1 - x0).TotalSeconds / (y1 - y0);
//next you have to compute the distance between one of your points and the target point on the known axis
double yDistance = target - y0;
//and then return the datetime that goes along with that point
return x0.AddSeconds(rate * yDistance);
}