计算一系列值的斜率

Nyx*_*Nyx 7 java math graphing

我有2个相等长度的数组.以下函数尝试使用这些数组计算斜率.它返回每个点之间的斜率的平均值.对于以下数据集,我似乎获得了与Excel和Google Docs不同的值.

        double[] x_values = { 1932, 1936, 1948, 1952, 1956, 1960, 1964, 1968,
            1972, 1976, 1980 };
    double[] y_values = { 197, 203, 198, 204, 212, 216, 218, 224, 223, 225,
            236 };



public static double getSlope(double[] x_values, double[] y_values)
        throws Exception {

    if (x_values.length != y_values.length)
        throw new Exception();

    double slope = 0;

    for (int i = 0; i < (x_values.length - 1); i++) {
        double y_2 = y_values[i + 1];
        double y_1 = y_values[i];

        double delta_y = y_2 - y_1;

        double x_2 = x_values[i + 1];
        double x_1 = x_values[i];

        double delta_x = x_2 - x_1;

        slope += delta_y / delta_x;
    }

    System.out.println(x_values.length);
    return slope / (x_values.length);
}
Run Code Online (Sandbox Code Playgroud)

产量

谷歌:0.755

getSlope():0.962121212121212

Excel:0.7501

NPE*_*NPE 5

我敢打赌,其他两种方法都在计算最小二乘拟合,而您却没有。

当我使用R验证这个猜想时,我也得到约0.755的斜率:

> summary(lm(y~x))

Call:
lm(formula = y ~ x)

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept) -1.265e+03  1.793e+02  -7.053 5.97e-05 ***
x            7.551e-01  9.155e-02   8.247 1.73e-05 ***
Run Code Online (Sandbox Code Playgroud)

相关数字是7.551e-01。还值得注意的是,该线的截距约为-1265。

这是最小二乘拟合的图片:

lm适合

关于在代码中实现此功能,请参阅使用Java计算最小二乘