code: private static double[] calcLinReg(double[] xData, double[] yData) {
          double sumX = 0;
          double sumY = 0;
          double prod = 0;
          int nstat = xData.length;
          double[] regCoef = new double[3]; //(intercept, gradient, r2)
  
          double meanYValue = mean(yData);
          double meanXValue = mean(xData);
  
          //calculating regression coefficients
          for (int i = 0; i < nstat; i++) {
              sumX += (xData[i] - meanXValue) * (xData[i] - meanXValue);
              sumY += (yData[i] - meanYValue) * (yData[i] - meanYValue);
              prod += (xData[i] - meanXValue) * (yData[i] - meanYValue);
          }
          if (sumX > 0 && sumY > 0) {
              regCoef[1] = prod / sumX;  //gradient
              regCoef[0] = meanYValue - regCoef[1] * meanXValue; //intercept
              regCoef[2] = Math.pow((prod / Math.sqrt(sumX * sumY)), 2); //r2
          }
          return regCoef;
      }
docs: Calcs coefficients of linear regression between x, y data
  @param xData the independent data array (x)
  @param yData the dependent data array (y)
  @return (intercept, gradient, r2)