我正在构建一个.net页面来模拟电子表格。该表包含此公式如何重新创建一个在C#中调用TREND()的Excel公式?
=ROUND(TREND(AA7:AE7,AA$4:AE$4,AF$4),1)
有人可以提供相当于C#的TREND()
吗?或者,如果任何人都可以提供一个快捷方式,那也可以;我对那里的数学不够熟悉,不知道是否有更简单的方法。
这里有一些示例编号,如果有帮助。
AA7:AE7 6 8 10 12 14
或 10.2 13.6 17.5 20.4 23.8
AA $ 4:AE $ 4 600 800 1000 1200 1400
AF $ 4 650
编辑:这是我想出来的,它似乎与我的电子表格产生相同的数字。
public static partial class Math2
{
public static double[] Trend(double[] known_y, double[] known_x, params double[] new_x)
{
// return array of new y values
double m, b;
Math2.LeastSquaresFitLinear(known_y, known_x, out m, out b);
List<double> new_y = new List<double>();
for (int j = 0; j < new_x.Length; j++)
{
double y = (m * new_x[j]) + b;
new_y.Add(y);
}
return new_y.ToArray();
}
// found at http://stackoverflow.com/questions/7437660/how-do-i-recreate-an-excel-formula-which-calls-trend-in-c
// with a few modifications
public static void LeastSquaresFitLinear(double[] known_y, double[] known_x, out double M, out double B)
{
if (known_y.Length != known_x.Length)
{
throw new ArgumentException("arrays are unequal lengths");
}
int numPoints = known_y.Length;
//Gives best fit of data to line Y = MC + B
double x1, y1, xy, x2, J;
x1 = y1 = xy = x2 = 0.0;
for (int i = 0; i < numPoints; i++)
{
x1 = x1 + known_x[i];
y1 = y1 + known_y[i];
xy = xy + known_x[i] * known_y[i];
x2 = x2 + known_x[i] * known_x[i];
}
M = B = 0;
J = ((double)numPoints * x2) - (x1 * x1);
if (J != 0.0)
{
M = (((double)numPoints * xy) - (x1 * y1))/J;
//M = Math.Floor(1.0E3 * M + 0.5)/1.0E3; // TODO this is disabled as it seems to product results different than excel
B = ((y1 * x2) - (x1 * xy))/J;
// B = Math.Floor(1.0E3 * B + 0.5)/1.0E3; // TODO assuming this is the same as above
}
}
}
我发现至少有一个sqaures拟合函数需要一组{x,y}并返回M和B.然后我可以使用M和B以及一组新的x值来生成y值作为趋势结果返回。这一切是否正确? – lincolnk
说实话,我对LINEST或TREND函数并不熟悉。在使用这些文件时它们会变得非常复杂,并且从文档来看,它们看起来有点不可靠(垃圾进入垃圾)。我认为您需要了解Excel函数的功能,并尝试在C#中重现结果。从我所能说的来看,并非易事。 –
链接不再有效 – Rocklan