Search code examples
c#mathematical-expressions

How do I calculate LINEST in C# with a zero intercept?


The normal Linest is easy, but I don't know how to "b is set equal to 0 and the m-values are adjusted to fit 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; }
}

Solution

  • This is a math question, not a coding question. 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 };
        }