I've searched and searched trying to find a simple class to calculate a slope and intercept from a set of points.
Here is the outcome, but I probably modify it to use LINQ rather then loops
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
public class Trendline { /// <summary> /// Get's the line's best fit slope of the line /// </summary> public double Slope { get; private set; } /// <summary> /// Get's the Mia /// </summary> public double Offset { get; private set; } public double[] ValuesX { get; private set; } public double[] ValuesY { get; private set; } private double sumY; private double sumX; private double sumXY; private double sumX2; private double n; public Trendline(double[] x, double[] y) { this.ValuesX = x; this.ValuesY = y; this.sumXY = this.calculateSumXsYsProduct(this.ValuesX, this.ValuesY); this.sumX = this.calculateSumXs(this.ValuesX); this.sumY = this.calculateSumYs(this.ValuesY); this.sumX2 = this.calculateSumXsSquare(this.ValuesX); this.n = this.ValuesX.Length; this.calculateSlope(); this.calculateOffset(); } public Trendline(double[] y) { //Assinging Y Values this.ValuesY = y; int length = y.Length; //Assinging X Values this.ValuesX = new double[length]; for (int i = 0; i < length; i++) { this.ValuesX[i] = i; } this.sumXY = this.calculateSumXsYsProduct(this.ValuesX, this.ValuesY); this.sumX = this.calculateSumXs(this.ValuesX); this.sumY = this.calculateSumYs(this.ValuesY); this.sumX2 = this.calculateSumXsSquare(this.ValuesX); this.n = this.ValuesX.Length; } public Trendline(double[][] xy) { double[] xs = new double[xy.Length]; double[] ys = new double[xy.Length]; for (int i = 0; i < xy.Length; i++) { xs[i] = xy[i][0]; ys[i] = xy[i][1]; } this.ValuesX = xs; this.ValuesY = ys; } private double calculateSumXsYsProduct(double[] xs, double[] ys) { double sum = 0; for (int i = 0; i < xs.Length; i++) { sum += xs[i] * ys[i]; } return sum; } private double calculateSumXs(double[] xs) { double sum = 0; foreach (double x in xs) { sum += x; } return sum; } private double calculateSumYs(double[] ys) { double sum = 0; foreach (double y in ys) { sum += y; } return sum; } private double calculateSumXsSquare(double[] xs) { double sum = 0; foreach (double x in xs) { sum += System.Math.Pow(x,2); } return sum; } private void calculateSlope() { try { Slope = (n * sumXY - sumX * sumY) / (n * sumX2 - System.Math.Pow(sumX,2)); } catch (DivideByZeroException) { Slope = 0; } } private void calculateOffset() { try { Slope = (sumY - Slope * sumX) / n; } catch (DivideByZeroException) { } } } |
One thought on “Useful Linear Trendline Class in C#”