상관 계수 계산 및 공식 적용
이 단계에서는 피어슨 상관 계수를 계산하기 위한 필요한 합계를 계산하도록 이전 프로그램을 확장합니다. correlation_input.c 파일을 수정하여 상관 공식 계산을 포함시킬 것입니다.
이전 파일을 엽니다.
cd ~/project
nano correlation_input.c
다음 구현으로 코드를 업데이트합니다.
#include <stdio.h>
#include <math.h>
#define MAX_POINTS 100
double calculatePearsonCorrelation(double x[], double y[], int n) {
double sum_x = 0, sum_y = 0, sum_xy = 0;
double sum_x_squared = 0, sum_y_squared = 0;
// 필요한 합계 계산
for (int i = 0; i < n; i++) {
sum_x += x[i];
sum_y += y[i];
sum_xy += x[i] * y[i];
sum_x_squared += x[i] * x[i];
sum_y_squared += y[i] * y[i];
}
// 피어슨 상관 계수 공식
double numerator = n * sum_xy - sum_x * sum_y;
double denominator = sqrt((n * sum_x_squared - sum_x * sum_x) *
(n * sum_y_squared - sum_y * sum_y));
return numerator / denominator;
}
int main() {
double x[MAX_POINTS], y[MAX_POINTS];
int n, i;
printf("Enter the number of data points (max %d): ", MAX_POINTS);
scanf("%d", &n);
printf("Enter x and y coordinates:\n");
for (i = 0; i < n; i++) {
printf("Point %d (x y): ", i + 1);
scanf("%lf %lf", &x[i], &y[i]);
}
double correlation = calculatePearsonCorrelation(x, y, n);
printf("\nData Points Entered:\n");
for (i = 0; i < n; i++) {
printf("Point %d: (%.2f, %.2f)\n", i + 1, x[i], y[i]);
}
printf("\nPearson Correlation Coefficient: %.4f\n", correlation);
return 0;
}
수학 라이브러리와 함께 프로그램을 컴파일합니다.
gcc -o correlation_input correlation_input.c -lm
샘플 데이터로 프로그램을 실행합니다.
./correlation_input
예시 출력:
Enter the number of data points (max 100): 5
Enter x and y coordinates:
Point 1 (x y): 1 2
Point 2 (x y): 2 4
Point 3 (x y): 3 5
Point 4 (x y): 4 4
Point 5 (x y): 5 5
Data Points Entered:
Point 1: (1.00, 2.00)
Point 2: (2.00, 4.00)
Point 3: (3.00, 5.00)
Point 4: (4.00, 4.00)
Point 5: (5.00, 5.00)
Pearson Correlation Coefficient: 0.8528
피어슨 상관 계수 계산에 대한 주요 내용:
- 필요한 합계 (x, y, xy, x², y²) 를 계산합니다.
- 피어슨 상관 계수 공식을 적용합니다.
- 계산에
math.h의 sqrt() 함수를 사용합니다.
- -1 과 1 사이의 상관 계수를 반환합니다.