我需要找到与日期相关的平均值。我有以下内容,需要在2015/05/01
50
找到平均运行值,那么我该如何编程呢?
double value = 0;
DateTime firstdate = Convert.ToDateTime("2015/02/01");
value = 20;
DateTime lastdate = Convert.ToDateTime("2015/06/01");
value = 60;
答案 0 :(得分:2)
所以基本上你想要在日期之间进行线性插值。
使用此:
static public double LinearInterpolation(double newOaDate, double firstOaDate, double lastOaDate, double firstValue, double lastValue)
{
if ((lastOaDate - firstOaDate) == 0)
{
return (firstValue + lastValue) / 2;
}
else
{
return firstValue + (newOaDate - firstOaDate) * (lastValue - firstValue) / (lastOaDate - firstOaDate);
}
}
用法:
DateTime firstDate = Convert.ToDateTime("2015/02/01");
double firstValue = 20;
DateTime lastDate = Convert.ToDateTime("2015/06/01");
double lastValue = 60;
DateTime newDate = Convert.ToDateTime("2015/05/01");
double newValue = LinearInterpolation(newDate.ToOADate(), firstDate.ToOADate(), lastDate.ToOADate(), firstValue, lastValue);
// RESULT: newValue = 49.666666666666671
那为什么newValue = 49.666666666666671
呢?因为并非所有月份都有30天,所以并非每个月的第1个月都是等距的。
如果你想获得精确的50
,那么你将被迫只使用月份值,并以智能方式使用线性插值(myDate.Month
等)。链接到线性插值:C# Linear Interpolation
答案 1 :(得分:0)
信息有限,所以我选择使用线性公式
功能:
private static double Calculate(KeyValuePair<DateTime, double> startDate, KeyValuePair<DateTime, double> endDate, DateTime targetDate)
{
// It's X.
var days = (endDate.Key - startDate.Key).TotalDays;
// It's Y.
var value = (endDate.Value - startDate.Value);
// You get the value of slope here.
var slope = value / days;
// Suppose x == 0 (change linear starting point to (0,0) in other word change starting date to date 0).
var constant = startDate.Value;
var daysToFind = (targetDate - startDate.Key).TotalDays;
return (slope * daysToFind) + constant;
}
用法:
CultureInfo culture = new CultureInfo("en-US");
var firstDate = new KeyValuePair<DateTime, double>(Convert.ToDateTime("2015/02/01", culture), 20);
var lastDate = new KeyValuePair<DateTime, double>(Convert.ToDateTime("2015/06/01", culture), 60);
var targetDate = Convert.ToDateTime("2015/05/01", culture);
var result = Calculate(firstDate, lastDate, targetDate);
通过这个,你可以预测你想要的任何日期的任何值(通过非常不确定的线性公式)。
像上面的答案一样。结果值为49.666666666666671,因为一个月中的天数不完全是30天。