두 개의 동일한 길이의 배열이 있습니다. 다음 함수는 이러한 배열을 사용하여 기울기를 계산하려고 시도합니다. 각 점 사이의 기울기 평균을 반환합니다. 다음 데이터 세트의 경우 Excel 및 Google 문서 도구와 다른 값을 얻는 것 같습니다.일련의 값의 기울기 계산
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);
}
출력
구글 : 0.755
getSlope() : 0.962121212121212
엑셀 : 0.7501
이 수치 예 [여기] (HTTP 참조 참조 : 여기
는 최소 제곱의 사진이 적합 .wikipedia.org/wiki/Simple_linear_regression)를 계산합니다. 이것은 코드 작성이 간단해야합니다. – karmanaut