<p>Google is not being my friend - it's been a long time since my stats class in college...I need to calculate the start and end points for a trendline on a graph - is there an easy way to do this? (working in C# but whatever language works for you)</p>

[{'answer_id': 43229, 'author': 'blank', 'author_id': 1348, 'author_profile': 'https://Stackoverflow.com/users/1348', 'pm_score': 5, 'selected': False, 'text': "<p>OK, here's my best pseudo math:</p>\n\n<p>The equation for your line is:</p>\n\n<p>Y = a + bX</p>\n\n<p>Where:</p>\n\n<p>b = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n)</p>\n\n<p>a = sum(y)/n - b(sum(x)/n)</p>\n\n<p>Where sum(xy) is the sum of all x*y etc. Not particularly clear I concede, but it's the best I can do without a sigma symbol :)</p>\n\n<p>... and now with added Sigma</p>\n\n<p>b = (&Sigma;(xy) - (&Sigma;x&Sigma;y)/n) / (&Sigma;(x^2) - (&Sigma;x)^2/n)</p>\n\n<p>a = (&Sigma;y)/n - b((&Sigma;x)/n)</p>\n\n<p>Where &Sigma;(xy) is the sum of all x*y etc. and n is the number of points</p>\n"}, {'answer_id': 43239, 'author': 'Adam Davis', 'author_id': 2915, 'author_profile': 'https://Stackoverflow.com/users/2915', 'pm_score': 5, 'selected': True, 'text': '<p>Given that the trendline is straight, find the slope by choosing any two points and calculating:</p>\n\n<p>(A)  slope = (y1-y2)/(x1-x2)</p>\n\n<p>Then you need to find the offset for the line.  The line is specified by the equation:</p>\n\n<p>(B)  y = offset + slope*x</p>\n\n<p>So you need to solve for offset.  Pick any point on the line, and solve for offset:</p>\n\n<p>(C)  offset = y - (slope*x)</p>\n\n<p>Now you can plug slope and offset into the line equation (B) and have the equation that defines your line.  If your line has noise you\'ll have to decide on an averaging algorithm, or use curve fitting of some sort.</p>\n\n<p>If your line isn\'t straight then you\'ll need to look into <a href="http://www.aip.org/tip/INPHFA/vol-9/iss-2/p24.html" rel="noreferrer">Curve fitting</a>, or <a href="http://mathworld.wolfram.com/LeastSquaresFitting.html" rel="noreferrer">Least Squares Fitting</a> - non trivial, but do-able.  You\'ll see the various types of curve fitting at the bottom of the least squares fitting webpage (exponential, polynomial, etc) if you know what kind of fit you\'d like.</p>\n\n<p>Also, if this is a one-off, use Excel.</p>\n'}, {'answer_id': 43334, 'author': 'Mike Woodhouse', 'author_id': 1060, 'author_profile': 'https://Stackoverflow.com/users/1060', 'pm_score': 2, 'selected': False, 'text': '<p>If you have access to Excel, look in the "Statistical Functions" section of the Function Reference within Help. For straight-line best-fit, you need SLOPE and INTERCEPT and the equations are right there.</p>\n\n<p>Oh, hang on, they\'re also defined online here: <a href="http://office.microsoft.com/en-us/excel/HP052092641033.aspx" rel="nofollow noreferrer">http://office.microsoft.com/en-us/excel/HP052092641033.aspx</a> for SLOPE, and there\'s a link to INTERCEPT. OF course, that assumes MS don\'t move the page, in which case try Googling for something like "SLOPE INTERCEPT EQUATION Excel site:microsoft.com" - the link given turned out third just now.</p>\n'}, {'answer_id': 47286, 'author': 'matt', 'author_id': 2646, 'author_profile': 'https://Stackoverflow.com/users/2646', 'pm_score': 5, 'selected': False, 'text': "<p>Thanks to all for your help - I was off this issue for a couple of days and just came back to it - was able to cobble this together - not the most elegant code, but it works for my purposes - thought I'd share if anyone else encounters this issue:</p>\n\n<pre><code>public class Statistics\n{\n    public Trendline CalculateLinearRegression(int[] values)\n    {\n        var yAxisValues = new List&lt;int&gt;();\n        var xAxisValues = new List&lt;int&gt;();\n\n        for (int i = 0; i &lt; values.Length; i++)\n        {\n            yAxisValues.Add(values[i]);\n            xAxisValues.Add(i + 1);\n        }\n\n        return new Trendline(yAxisValues, xAxisValues);\n    }\n}\n\npublic class Trendline\n{\n    private readonly IList&lt;int&gt; xAxisValues;\n    private readonly IList&lt;int&gt; yAxisValues;\n    private int count;\n    private int xAxisValuesSum;\n    private int xxSum;\n    private int xySum;\n    private int yAxisValuesSum;\n\n    public Trendline(IList&lt;int&gt; yAxisValues, IList&lt;int&gt; xAxisValues)\n    {\n        this.yAxisValues = yAxisValues;\n        this.xAxisValues = xAxisValues;\n\n        this.Initialize();\n    }\n\n    public int Slope { get; private set; }\n    public int Intercept { get; private set; }\n    public int Start { get; private set; }\n    public int End { get; private set; }\n\n    private void Initialize()\n    {\n        this.count = this.yAxisValues.Count;\n        this.yAxisValuesSum = this.yAxisValues.Sum();\n        this.xAxisValuesSum = this.xAxisValues.Sum();\n        this.xxSum = 0;\n        this.xySum = 0;\n\n        for (int i = 0; i &lt; this.count; i++)\n        {\n            this.xySum += (this.xAxisValues[i]*this.yAxisValues[i]);\n            this.xxSum += (this.xAxisValues[i]*this.xAxisValues[i]);\n        }\n\n        this.Slope = this.CalculateSlope();\n        this.Intercept = this.CalculateIntercept();\n        this.Start = this.CalculateStart();\n        this.End = this.CalculateEnd();\n    }\n\n    private int CalculateSlope()\n    {\n        try\n        {\n            return ((this.count*this.xySum) - (this.xAxisValuesSum*this.yAxisValuesSum))/((this.count*this.xxSum) - (this.xAxisValuesSum*this.xAxisValuesSum));\n        }\n        catch (DivideByZeroException)\n        {\n            return 0;\n        }\n    }\n\n    private int CalculateIntercept()\n    {\n        return (this.yAxisValuesSum - (this.Slope*this.xAxisValuesSum))/this.count;\n    }\n\n    private int CalculateStart()\n    {\n        return (this.Slope*this.xAxisValues.First()) + this.Intercept;\n    }\n\n    private int CalculateEnd()\n    {\n        return (this.Slope*this.xAxisValues.Last()) + this.Intercept;\n    }\n}\n</code></pre>\n"}, {'answer_id': 713274, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Regarding a previous answer</p>\n\n<p>if <em>(B) y = offset + slope*x</em></p>\n\n<p>then <em>(C) offset = y/(slope*x)</em> is wrong</p>\n\n<p>(C) should be:</p>\n\n<p><em>offset = y-(slope*x)</em></p>\n\n<p>See:\n<a href="http://zedgraph.org/wiki/index.php?title=Trend" rel="nofollow noreferrer">http://zedgraph.org/wiki/index.php?title=Trend</a></p>\n'}, {'answer_id': 14235891, 'author': 'franchsesko', 'author_id': 1961279, 'author_profile': 'https://Stackoverflow.com/users/1961279', 'pm_score': 0, 'selected': False, 'text': "<p>Thank You so much for the solution, I was scratching my head.<br>\nHere's how I applied the solution in Excel.<br>\nI successfully used the two functions given by MUHD in Excel:<br>\na = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n)<br>\nb = sum(y)/n - b(sum(x)/n)<br>\n(careful my a and b are the b and a in MUHD's solution).<br>\n<br>\n- Made 4 columns, for example:<br>\n  NB: my values y values are in B3:B17, so I have n=15;<br>\n      my x values are 1,2,3,4...15.<br>\n  1. Column B: Known x's<br>\n  2. Column C: Known y's<br>\n  3. Column D: The computed trend line<br>\n  4. Column E: B values * C values (E3=B3*C3, E4=B4*C4, ..., E17=B17*C17)<br>\n  5. Column F: x squared values<br>\nI then sum the columns B,C and E, the sums go in line 18 for me, so I have B18 as sum of Xs, C18 as sum of Ys, E18 as sum of X*Y, and F18 as sum of squares.<br>\nTo compute a, enter the followin formula in any cell (F35 for me):<br>\nF35=(E18-(B18*C18)/15)/(F18-(B18*B18)/15)<br>\nTo compute b (in F36 for me):<br>\nF36=C18/15-F35*(B18/15)<br>\nColumn D values, computing the trend line according to the y = ax + b:<br>\nD3=$F$35*B3+$F$36, D4=$F$35*B4+$F$36 and so on (until D17 for me).<br>\n<br>\nSelect the column datas (C2:D17) to make the graph.<br>\nHTH.</p>\n"}, {'answer_id': 15799351, 'author': 'Thymine', 'author_id': 356218, 'author_profile': 'https://Stackoverflow.com/users/356218', 'pm_score': 4, 'selected': False, 'text': '<p>Here is a very quick (and semi-dirty) implementation of <a href="https://stackoverflow.com/a/43229/356218">Bedwyr Humphreys\'s answer</a>.  The interface should be compatible with <a href="https://stackoverflow.com/a/47286/356218">@matt</a>\'s answer as well, but uses <code>decimal</code> instead of <code>int</code> and uses more IEnumerable concepts to hopefully make it easier to use and read.</p>\n\n<p><code>Slope</code> is <code>b</code>, <code>Intercept</code> is <code>a</code></p>\n\n<pre><code>public class Trendline\n{\n    public Trendline(IList&lt;decimal&gt; yAxisValues, IList&lt;decimal&gt; xAxisValues)\n        : this(yAxisValues.Select((t, i) =&gt; new Tuple&lt;decimal, decimal&gt;(xAxisValues[i], t)))\n    { }\n    public Trendline(IEnumerable&lt;Tuple&lt;Decimal, Decimal&gt;&gt; data)\n    {\n        var cachedData = data.ToList();\n\n        var n = cachedData.Count;\n        var sumX = cachedData.Sum(x =&gt; x.Item1);\n        var sumX2 = cachedData.Sum(x =&gt; x.Item1 * x.Item1);\n        var sumY = cachedData.Sum(x =&gt; x.Item2);\n        var sumXY = cachedData.Sum(x =&gt; x.Item1 * x.Item2);\n\n        //b = (sum(x*y) - sum(x)sum(y)/n)\n        //      / (sum(x^2) - sum(x)^2/n)\n        Slope = (sumXY - ((sumX * sumY) / n))\n                    / (sumX2 - (sumX * sumX / n));\n\n        //a = sum(y)/n - b(sum(x)/n)\n        Intercept = (sumY / n) - (Slope * (sumX / n));\n\n        Start = GetYValue(cachedData.Min(a =&gt; a.Item1));\n        End = GetYValue(cachedData.Max(a =&gt; a.Item1));\n    }\n\n    public decimal Slope { get; private set; }\n    public decimal Intercept { get; private set; }\n    public decimal Start { get; private set; }\n    public decimal End { get; private set; }\n\n    public decimal GetYValue(decimal xValue)\n    {\n        return Intercept + Slope * xValue;\n    }\n}\n</code></pre>\n'}, {'answer_id': 48136019, 'author': 'Magn3144', 'author_id': 7769419, 'author_profile': 'https://Stackoverflow.com/users/7769419', 'pm_score': 1, 'selected': False, 'text': '<p>This is the way i calculated the slope:\nSource: <a href="http://classroom.synonym.com/calculate-trendline-2709.html" rel="nofollow noreferrer">http://classroom.synonym.com/calculate-trendline-2709.html</a></p>\n\n<pre><code>class Program\n    {\n        public double CalculateTrendlineSlope(List&lt;Point&gt; graph)\n        {\n            int n = graph.Count;\n            double a = 0;\n            double b = 0;\n            double bx = 0;\n            double by = 0;\n            double c = 0;\n            double d = 0;\n            double slope = 0;\n\n            foreach (Point point in graph)\n            {\n                a += point.x * point.y;\n                bx = point.x;\n                by = point.y;\n                c += Math.Pow(point.x, 2);\n                d += point.x;\n            }\n            a *= n;\n            b = bx * by;\n            c *= n;\n            d = Math.Pow(d, 2);\n\n            slope = (a - b) / (c - d);\n            return slope;\n        }\n    }\n\n    class Point\n    {\n        public double x;\n        public double y;\n    }\n</code></pre>\n'}, {'answer_id': 51140331, 'author': 'Todd Skelton', 'author_id': 1212994, 'author_profile': 'https://Stackoverflow.com/users/1212994', 'pm_score': 1, 'selected': False, 'text': '<p>Here\'s what I ended up using.</p>\n\n<pre><code>public class DataPoint&lt;T1,T2&gt;\n{\n    public DataPoint(T1 x, T2 y)\n    {\n        X = x;\n        Y = y;\n    }\n\n    [JsonProperty("x")]\n    public T1 X { get; }\n\n    [JsonProperty("y")]\n    public T2 Y { get; }\n}\n\npublic class Trendline\n{\n    public Trendline(IEnumerable&lt;DataPoint&lt;long, decimal&gt;&gt; dataPoints)\n    {\n        int count = 0;\n        long sumX = 0;\n        long sumX2 = 0;\n        decimal sumY = 0;\n        decimal sumXY = 0;\n\n        foreach (var dataPoint in dataPoints)\n        {\n            count++;\n            sumX += dataPoint.X;\n            sumX2 += dataPoint.X * dataPoint.X;\n            sumY += dataPoint.Y;\n            sumXY += dataPoint.X * dataPoint.Y;\n        }\n\n        Slope = (sumXY - ((sumX * sumY) / count)) / (sumX2 - ((sumX * sumX) / count));\n        Intercept = (sumY / count) - (Slope * (sumX / count));\n    }\n\n    public decimal Slope { get; private set; }\n    public decimal Intercept { get; private set; }\n    public decimal Start { get; private set; }\n    public decimal End { get; private set; }\n\n    public decimal GetYValue(decimal xValue)\n    {\n        return Slope * xValue + Intercept;\n    }\n}\n</code></pre>\n\n<p>My data set is using a Unix timestamp for the x-axis and a decimal for the y. Change those datatypes to fit your need. I do all the sum calculations in one iteration for the best possible performance.</p>\n'}, {'answer_id': 59964271, 'author': 'jonyB', 'author_id': 10564382, 'author_profile': 'https://Stackoverflow.com/users/10564382', 'pm_score': 0, 'selected': False, 'text': '<p>If anyone needs the JS code for calculating the trendline of many points on a graph, here\'s what worked for us in the end:</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>/**@typedef {{\r\n * x: Number;\r\n * y:Number;\r\n * }} Point\r\n * @param {Point[]} data\r\n * @returns {Function} */\r\nfunction _getTrendlineEq(data) {\r\n    const xySum = data.reduce((acc, item) =&gt; {\r\n        const xy = item.x * item.y\r\n        acc += xy\r\n        return acc\r\n    }, 0)\r\n    const xSum = data.reduce((acc, item) =&gt; {\r\n        acc += item.x\r\n        return acc\r\n    }, 0)\r\n    const ySum = data.reduce((acc, item) =&gt; {\r\n        acc += item.y\r\n        return acc\r\n    }, 0)\r\n    const aTop = (data.length * xySum) - (xSum * ySum)\r\n    const xSquaredSum = data.reduce((acc, item) =&gt; {\r\n        const xSquared = item.x * item.x\r\n        acc += xSquared\r\n        return acc\r\n    }, 0)\r\n    const aBottom = (data.length * xSquaredSum) - (xSum * xSum)\r\n    const a = aTop / aBottom\r\n    const bTop = ySum - (a * xSum)\r\n    const b = bTop / data.length\r\n    return function trendline(x) {\r\n        return a * x + b\r\n    }\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>It takes an array of (x,y) points and returns the function of a y given a certain x\nHave fun :)</p>\n'}, {'answer_id': 62789036, 'author': 'user13889781', 'author_id': 13889781, 'author_profile': 'https://Stackoverflow.com/users/13889781', 'pm_score': 0, 'selected': False, 'text': "<p>Here's a working example in golang. I searched around and found this page and converted this over to what I needed. Hope someone else can find it useful.</p>\n<pre><code>// https://classroom.synonym.com/calculate-trendline-2709.html\npackage main\n\nimport (\n    &quot;fmt&quot;\n    &quot;math&quot;\n)\n\nfunc main() {\n\n    graph := [][]float64{\n        {1, 3},\n        {2, 5},\n        {3, 6.5},\n    }\n\n    n := len(graph)\n\n    // get the slope\n    var a float64\n    var b float64\n    var bx float64\n    var by float64\n    var c float64\n    var d float64\n    var slope float64\n\n    for _, point := range graph {\n\n        a += point[0] * point[1]\n        bx += point[0]\n        by += point[1]\n        c += math.Pow(point[0], 2)\n        d += point[0]\n\n    }\n\n    a *= float64(n)           // 97.5\n    b = bx * by               // 87\n    c *= float64(n)           // 42\n    d = math.Pow(d, 2)        // 36\n    slope = (a - b) / (c - d) // 1.75\n\n    // calculating the y-intercept (b) of the Trendline\n    var e float64\n    var f float64\n\n    e = by                            // 14.5\n    f = slope * bx                    // 10.5\n    intercept := (e - f) / float64(n) // (14.5 - 10.5) / 3 = 1.3\n\n    // output\n    fmt.Println(slope)\n    fmt.Println(intercept)\n\n}\n</code></pre>\n"}, {'answer_id': 67130721, 'author': 'Gregg Reno', 'author_id': 264604, 'author_profile': 'https://Stackoverflow.com/users/264604', 'pm_score': 2, 'selected': False, 'text': "<p>I converted Matt's code to Java so I could use it in Android with the MPAndroidChart library.  Also used double values instead of integer values:</p>\n<pre><code>ArrayList&lt;Entry&gt; yValues2 = new ArrayList&lt;&gt;();\n\nArrayList&lt;Double &gt; xAxisValues = new ArrayList&lt;Double&gt;();\nArrayList&lt;Double&gt; yAxisValues = new ArrayList&lt;Double&gt;();\n\nfor (int i = 0; i &lt; readings.size(); i++)\n{\n    r = readings.get(i);\n    yAxisValues.add(r.value);\n    xAxisValues.add((double)i + 1);\n}\n\nTrendLine tl = new TrendLine(yAxisValues, xAxisValues);\n\n//Create the y values for the trend line\ndouble currY = tl.Start;\nfor (int i = 0; i &lt; readings.size(); ++ i) {\n    yValues2.add(new Entry(i, (float) currY));\n    currY = currY + tl.Slope;\n}\n\n...\n\npublic class TrendLine\n{\n    private ArrayList&lt;Double&gt; xAxisValues = new ArrayList&lt;Double&gt;();\n    private ArrayList&lt;Double&gt; yAxisValues = new ArrayList&lt;Double&gt;();\n\n    private int count;\n    private double xAxisValuesSum;\n    private double xxSum;\n    private double xySum;\n    private double yAxisValuesSum;\n\n    public TrendLine(ArrayList&lt;Double&gt; yAxisValues, ArrayList&lt;Double&gt; xAxisValues)\n    {\n        this.yAxisValues = yAxisValues;\n        this.xAxisValues = xAxisValues;\n\n        this.Initialize();\n    }\n\n    public double Slope;\n    public double Intercept;\n    public double Start;\n    public double End;\n\n    private double getArraySum(ArrayList&lt;Double&gt; arr) {\n        double sum = 0;\n        for (int i = 0; i &lt; arr.size(); ++i) {\n            sum = sum + arr.get(i);\n        }\n        return sum;\n    }\n    private void Initialize()\n    {\n        this.count = this.yAxisValues.size();\n        this.yAxisValuesSum = getArraySum(this.yAxisValues);\n        this.xAxisValuesSum = getArraySum(this.xAxisValues);\n        this.xxSum = 0;\n        this.xySum = 0;\n\n        for (int i = 0; i &lt; this.count; i++)\n        {\n            this.xySum += (this.xAxisValues.get(i)*this.yAxisValues.get(i));\n            this.xxSum += (this.xAxisValues.get(i)*this.xAxisValues.get(i));\n        }\n\n        this.Slope = this.CalculateSlope();\n        this.Intercept = this.CalculateIntercept();\n        this.Start = this.CalculateStart();\n        this.End = this.CalculateEnd();\n    }\n\n    private double CalculateSlope()\n    {\n        try\n        {\n            return ((this.count*this.xySum) - (this.xAxisValuesSum*this.yAxisValuesSum))/((this.count*this.xxSum) - (this.xAxisValuesSum*this.xAxisValuesSum));\n        }\n        catch (Exception e)\n        {\n            return 0;\n        }\n    }\n\n    private double CalculateIntercept()\n    {\n        return (this.yAxisValuesSum - (this.Slope*this.xAxisValuesSum))/this.count;\n    }\n\n    private double CalculateStart()\n    {\n        return (this.Slope*this.xAxisValues.get(0)) + this.Intercept;\n    }\n\n    private double CalculateEnd()\n    {\n        return (this.Slope*this.xAxisValues.get(this.xAxisValues.size()-1)) + this.Intercept;\n    }\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/43224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2646/']