首页 > 解决方案 > Java 错误的趋势线计算

问题描述

我有个问题。我试图使用这个包来计算趋势线的斜率:https ://stackoverflow.com/a/17634728/10673107 。所以我有以下主要功能:

public static void main(String[] args) {
    Long[] arrOpenTime = new Long[] {0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L};
    double[] arrData = new double[] {62950.326, 62996.7789, 63021.8868, 63073.9042, 63064.8436, 63028.78, 63014.8, 62806.0692, 62651.2262, 62467.2976};
    getTrendline(arrData, arrOpenTime, 10L);
}

这是功能getTrendLine()

private static void getTrendline(double[] data, Long[] openTimes, long timestampToPredict) {

    // Start a regression class of order 2--linear regression.
    PolyTrendLine polyTrendLine = new PolyTrendLine(2);

    // Add all the data to the regression analysis.
    polyTrendLine.setValues(data, openTimes);

    // Get coefficients for the polynomial.
    System.out.println(polyTrendLine.predict(timestampToPredict));
    System.out.println(polyTrendLine.getCoef());
    
}

现在我本来预计getCoef()会打印趋势线的斜率(在我的情况下:)-48.84,但我得到以下信息:

Array2DRowRealMatrix{{62915.24316},{110.2559048485},{-17.6773151515}}

我不知道这个包是否能够满足我的需求,因为我的主要目标是获得所有价值来创建论坛。这些给定值的正确公式是: 在此处输入图像描述

如何计算值:

使用数据点数组。请告诉我!

标签: javamath

解决方案


您链接的 SO 答案只是Apache Commons stats 包的包装器。但是你不需要那个包装器,你的问题很简单,可以直接使用那个包:

import org.apache.commons.math3.stat.regression.SimpleRegression;

public class Regression {
    public static void main(String[] args) {
        double[][] data = {
            {0.0, 62950.326},
            {1.0, 62996.7789},
            {2.0, 63021.8868},
            {3.0, 63073.9042},
            {4.0, 63064.8436},
            {5.0, 63028.78},
            {6.0, 63014.8},
            {7.0, 62806.0692},
            {8.0, 62651.2262},
            {9.0, 62467.2976}
        };

        SimpleRegression regression = new SimpleRegression();
        regression.addData(data);
        regression.regress();

        System.out.println(regression.getSlope());
        System.out.println(regression.getIntercept());
    }
}

推荐阅读