Calculating the slope of a series of values

前端 未结 4 1746
名媛妹妹
名媛妹妹 2021-02-15 11:32

I have 2 arrays of equal length. The following function attempts to calculate the slope using these arrays. It returns the average of the slope between each points. For the foll

4条回答
  •  余生分开走
    2021-02-15 12:21

    Edit: use Apache Commons Math class SimpleRegression if that's an option. Else, here's a method that calculates slope and also intercept, should yield the same results as excel and apache:

    private static double intercept(List yList, List xList) {
        if (yList.size() != xList.size())
            throw new IllegalArgumentException("Number of y and x must be the same");
        if (yList.size() < 2)
            throw new IllegalArgumentException("Need at least 2 y, x");
    
        double yAvg = average(yList);
        double xAvg = average(xList);
    
        double sumNumerator = 0d;
        double sumDenominator = 0d;
        for (int i = 0; i < yList.size(); i++) {
            double y = yList.get(i);
            double x = xList.get(i);
            double yDiff = y - yAvg;
            double xDiff = x - xAvg;
            double numerator = xDiff * yDiff;
            double denominator = xDiff * xDiff;
            sumNumerator += numerator;
            sumDenominator += denominator;
        }
    
        double slope = sumNumerator / sumDenominator;
        double intercept = yAvg - (slope * xAvg);
        return intercept;
    }
    
    private static double average(Collection doubles) {
        return doubles.stream().collect(Collectors.averagingDouble(d -> d));
    }
    

    Sources: Excel doc for SLOPE Excel doc for INTERCEPT

提交回复
热议问题