如何在C#中重新创建调用TREND()的Excel公式?

5

我正在构建一个 .net 页面以模拟电子表格。该表格包含以下公式:

=ROUND(TREND(AA7:AE7,AA$4:AE$4,AF$4),1)

有人能提供TREND()的C#等效代码吗?或者如果有人可以提供一个快捷方式也可以; 我对数学不是很熟悉,不知道是否有更简单的方法。以下是一些示例数字以帮助理解。 AA7:AE7 6 8 10 12 1410.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 https://dev59.com/a1vUa4cB1Zd3GeqPsVJg
    // 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
        }
    }

}
3个回答

6

这篇文章非常有帮助,因为我们需要在C#中重新创建它。感谢上面Jeff的回答,我使用以下代码重新创建了该公式:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;

public static class MathHelper
{
    /// <summary>
    /// Gets the value at a given X using the line of best fit (Least Square Method) to determine the equation
    /// </summary>
    /// <param name="points">Points to calculate the value from</param>
    /// <param name="x">Function input</param>
    /// <returns>Value at X in the given points</returns>
    public static float LeastSquaresValueAtX(List<PointF> points, float x)
    {
        float slope = SlopeOfPoints(points);
        float yIntercept = YInterceptOfPoints(points, slope);

        return (slope * x) + yIntercept;
    }

    /// <summary>
    /// Gets the slope for a set of points using the formula:
    /// m = ∑ (x-AVG(x)(y-AVG(y)) / ∑ (x-AVG(x))²
    /// </summary>
    /// <param name="points">Points to calculate the Slope from</param>
    /// <returns>SlopeOfPoints</returns>
    private static float SlopeOfPoints(List<PointF> points)
    {
        float xBar = points.Average(p => p.X);
        float yBar = points.Average(p => p.Y);

        float dividend = points.Sum(p => (p.X - xBar) * (p.Y - yBar));
        float divisor = (float)points.Sum(p => Math.Pow(p.X - xBar, 2));

        return dividend / divisor;            
    }

    /// <summary>
    /// Gets the Y-Intercept for a set of points using the formula:
    /// b = AVG(y) - m( AVG(x) )
    /// </summary>
    /// <param name="points">Points to calculate the intercept from</param>
    /// <returns>Y-Intercept</returns>
    private static float YInterceptOfPoints(List<PointF> points, float slope)
    { 
        float xBar = points.Average(p => p.X);
        float yBar = points.Average(p => p.Y);

        return yBar - (slope * xBar);        
    }       
}

由于 Point 使用整数来定义其值,我选择使用 PointF,因为在我们的应用程序中可以有许多小数位。如果我在某个地方错误地陈述了术语,请纠正我,尽管我更多的时间是在编写代码而不是开发此类算法。

这肯定比等待 Excel Interop 在后台加载以使用工作簿的趋势方法更快。


6

我找到了一个最小二乘拟合函数,它接受一组{x,y}并返回M和B。然后我可以使用M和B与新的x值集合生成y值,作为趋势结果返回。这样正确吗? - lincolnk
说实话,我对LINEST或TREND函数并不太熟悉。在使用这些函数时有很多要考虑的因素,并且根据文档来看,它们似乎有点不可靠(垃圾进垃圾出)。我认为你需要了解Excel函数的作用,并尝试在C#中复现结果。从我所了解的情况来看,这并不是一件容易的事情。 - Jeff Reddy
链接已失效。 - Rocklan

0

感谢提供的代码,已经用JavaScript重新创建。

function LeastSquaresFitLinear(known_y, known_x, offset_x)
{
    if (known_y.length != known_x.length) return false; //("arrays are unequal lengths");
    var numPoints = known_y.length;

    var x1=0, y1=0, xy=0, x2=0, J, M, B;
    for (var i = 0; i < numPoints; i++)
    {
        known_x[i] -= offset_x;
        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];
    }

    J = (numPoints * x2) - (x1 * x1);
    if (J != 0.0)
    {
        M = ((numPoints * xy) - (x1 * y1)) / J;
        B = ((y1 * x2) - (x1 * xy)) / J;
    }
    return [M,B];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接