【问题标题】:How do I calculate LINEST in C# with a zero intercept?如何在 C# 中以零截距计算 LINEST?
【发布时间】:2015-02-26 05:57:39
【问题描述】:

正常的Linest很简单,但我不知道如何“设置b等于0并且调整m值以适应y = mx。”

static class Program
{
    static void Main(string[] args)
    {
        var yValues = new double[] { 1, 9, 5, 7 };
        var xValues = new double[] { 0, 4, 2, 3 };


        var noConst = Linest(yValues, xValues);
        Console.WriteLine("m = {0}, b = {1}", noConst.Slope, noConst.Intercept);


    }

    public static LineSpec Linest(IList<double> yValues, IList<double> xValues)
    {
        var yAvg = yValues.Sum() / yValues.Count;
        var xAvg = xValues.Sum() / xValues.Count;

        double upperSum = 0;
        double lowerSum = 0;
        for (var i = 0; i < yValues.Count; i++)
        {
            upperSum += (xValues[i] - xAvg) * (yValues[i] - yAvg);
            lowerSum += (xValues[i] - xAvg) * (xValues[i] - xAvg);
        }

        var m = upperSum / lowerSum;
        var b = yAvg - m * xAvg;
        return new LineSpec() { Slope = m, Intercept = b };
    }

}

struct LineSpec
{
    public double Slope { get; set; }
    public double Intercept { get; set; }
}

【问题讨论】:

  • 我不明白你在问什么。你不知道如何用零截距计算 LINEST 吗?或者您在实现您在 C# 中使用的方法时遇到特定问题?如果是前者,那么您的问题最好来自数学 SE。如果是后者,您应该提供有关您的实现的详细信息,最好是代码,并指出您遇到问题的地方。

标签: c# mathematical-expressions


【解决方案1】:

这是一道数学题,不是编码题。 Use linear regression without the intercept term.


    public static LineSpec LinestConst(IList<double> yValues, IList<double> xValues)
    {
        var yAvg = yValues.Sum() / yValues.Count;
        var xAvg = xValues.Sum() / xValues.Count;

        double upperSum = 0;
        double lowerSum = 0;
        for (var i = 0; i < yValues.Count; i++)
        {
            upperSum += (xValues[i] * yValues[i] );
            lowerSum += (xValues[i] * xValues[i] );
        }

        var m = upperSum / lowerSum;
        var b = 0;
        return new LineSpec() { Slope = m, Intercept = b };
    }

【讨论】:

    猜你喜欢
    • 2015-11-13
    • 2023-01-13
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 2015-08-24
    • 2020-07-08
    • 1970-01-01
    相关资源
    最近更新 更多