Calculation of the slope of a series of values

I have 2 arrays of the same length. The following function attempts to calculate the slope using these arrays. It returns the average slope between the points. For the next dataset, I seem to get different values โ€‹โ€‹than Excel and 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);
}

Output

Google: 0.755

getSlope (): 0.96212121212121212

Excel: 0.7501

+5
source share
3 answers

I am sure that the other two methods calculate the smallest squares by size , while you do not.

When I test this hypothesis with R , I also get a slope of about 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 ***

The corresponding number is 7.551e-01. It is also worth noting that the line has an interception of about -1265.

:

lm fit

, . java

+4

, . (0,0), (1000,1000) (1001, 2000) (0,0), (1,1) (2, 1001). 1 1000, .

: http://en.wikipedia.org/wiki/Least_squares, , .

: java.lang.Exception. , . , , java.lang.Exception, .

+2

You must share on x_values.length - 1. The number of slopes in pairs.

Edit: The Wiki example in my comments shows how to calculate alpha and beta, which determines the slope of a linear regression line.

-1
source

All Articles