As a developer we sometime need to implement excel function in code for meeting client’s requirement. Here I will share code for Excel LINEST function in apex. You can check LINEST function/method of excel here.
See below code method, you can use it in your apex class.
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 |
/** * @author : 799 The Coder * @date : 1 Feb 2016 * @description : This method returns a Decimal which is slope for the passed List of y coordinates (Equivalent to LINEST(y's,,TRUE,TRUE)) * @param : List<Decimal> ySet * @return : Decimal (slope) */ public static Decimal getSlopeFromYset(List < Decimal > ySet) { Decimal slope = 0.0; Decimal sumX = 0.0, sumY = 0.0, sumXY = 0.0, sumX2 = 0.0; List < Decimal > xSet = new List < Decimal > (); // Setting up set of X with default set {1,2,3,...n} decimal x = 1; for (Decimal tempY: ySet) { xSet.add(x++); } // No of elements in Y integer N = ySet.size(); for (integer i = 0; i < ySet.size(); i++) { Decimal xy = xSet.get(i) * ySet.get(i); Decimal x2 = xSet.get(i) * xSet.get(i); sumX = sumX + xSet.get(i); sumY = sumY + ySet.get(i); sumXY = sumXY + xy; sumX2 = sumX2 + x2; } slope = ((N * sumXY) - (sumX * sumY)) / ((N * sumX2) - (sumX * sumX)); return slope; } |
It will save your time if you need to write it from scratch in apex. I am open for your valuable feedback.
Happy Coding 🙂