C 언어로 피어슨 상관 계수 계산하기

CBeginner
지금 연습하기

소개

이 실습에서는 C 언어로 피어슨 상관 계수를 계산하는 방법을 배웁니다. 이 실습은 짝지어진 (x, y) 데이터를 읽고, 필요한 합계를 계산하고, 공식을 사용하여 상관 계수를 계산하는 세 가지 주요 단계로 구성됩니다. 사용자가 데이터 점을 입력할 수 있도록 C 프로그램을 만들고, 프로그램은 상관 분석을 수행하고 결과를 출력합니다.

이 실습은 데이터 입력 기능의 구현부터 상관 공식에 필요한 합계의 계산, 그리고 마지막으로 상관 계수의 출력까지 단계별 가이드를 제공합니다.

짝지어진 (x, y) 데이터 읽기

이 단계에서는 C 언어로 피어슨 상관 계수를 계산하기 위해 짝지어진 (x, y) 데이터를 읽는 방법을 배웁니다. 사용자가 짝지어진 숫자 데이터를 입력하고, 이를 추가 분석을 위해 저장할 수 있도록 프로그램을 만들 것입니다.

먼저, 데이터 입력 기능을 위한 C 소스 파일을 생성해 봅시다.

cd ~/project
nano correlation_input.c

이제 다음 코드를 파일에 추가합니다.

#include <stdio.h>
#define MAX_POINTS 100

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]);
    }

    printf("\nData Points Entered:\n");
    for (i = 0; i < n; i++) {
        printf("Point %d: (%.2f, %.2f)\n", i + 1, x[i], y[i]);
    }

    return 0;
}

프로그램을 컴파일합니다.

gcc -o correlation_input correlation_input.c

프로그램을 실행하고 몇 가지 샘플 데이터를 입력해 봅시다.

./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)

코드를 살펴보겠습니다.

  1. 메모리 초과를 방지하기 위해 최대 데이터 점 개수 (MAX_POINTS) 를 정의합니다.
  2. 프로그램은 사용자에게 데이터 점의 개수를 입력하도록 요청합니다.
  3. 각 점에 대한 x 및 y 좌표를 입력할 수 있도록 합니다.
  4. 마지막으로 입력된 데이터 점을 출력하여 입력을 확인합니다.

상관 계수 계산 및 공식 적용

이 단계에서는 피어슨 상관 계수를 계산하기 위한 필요한 합계를 계산하도록 이전 프로그램을 확장합니다. 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

피어슨 상관 계수 계산에 대한 주요 내용:

  1. 필요한 합계 (x, y, xy, x², y²) 를 계산합니다.
  2. 피어슨 상관 계수 공식을 적용합니다.
  3. 계산에 math.hsqrt() 함수를 사용합니다.
  4. -1 과 1 사이의 상관 계수를 반환합니다.

상관 계수 출력

이 마지막 단계에서는 피어슨 상관 계수에 대한 포괄적인 해석을 제공하고 사용자 친화적인 출력을 생성하도록 프로그램을 개선합니다.

이전 파일을 엽니다.

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;
}

void interpretCorrelation(double correlation) {
    printf("\n상관 계수 해석:\n");
    printf("상관 계수 값: %.4f\n", correlation);

    if (correlation > 0.8) {
        printf("강한 양의 상관관계\n");
    } else if (correlation > 0.5) {
        printf("중간 양의 상관관계\n");
    } else if (correlation > 0.3) {
        printf("약한 양의 상관관계\n");
    } else if (correlation > -0.3) {
        printf("선형 상관관계 없음\n");
    } else if (correlation > -0.5) {
        printf("약한 음의 상관관계\n");
    } else if (correlation > -0.8) {
        printf("중간 음의 상관관계\n");
    } else {
        printf("강한 음의 상관관계\n");
    }
}

int main() {
    double x[MAX_POINTS], y[MAX_POINTS];
    int n, i;

    printf("피어슨 상관 계수 계산기\n");
    printf("------------------------\n");
    printf("데이터 점 개수를 입력하세요 (최대 %d): ", MAX_POINTS);
    scanf("%d", &n);

    printf("x 및 y 좌표를 입력하세요:\n");
    for (i = 0; i < n; i++) {
        printf("점 %d (x y): ", i + 1);
        scanf("%lf %lf", &x[i], &y[i]);
    }

    double correlation = calculatePearsonCorrelation(x, y, n);

    printf("\n입력된 데이터 점:\n");
    for (i = 0; i < n; i++) {
        printf("점 %d: (%.2f, %.2f)\n", i + 1, x[i], y[i]);
    }

    interpretCorrelation(correlation);

    return 0;
}

프로그램을 컴파일합니다.

gcc -o correlation_calculator correlation_input.c -lm

샘플 데이터로 프로그램을 실행합니다.

./correlation_calculator

예시 출력:

피어슨 상관 계수 계산기
------------------------
데이터 점 개수를 입력하세요 (최대 100): 5
x 및 y 좌표를 입력하세요:
점 1 (x y): 1 2
점 2 (x y): 2 4
점 3 (x y): 3 5
점 4 (x y): 4 4
점 5 (x y): 5 5

입력된 데이터 점:
점 1: (1.00, 2.00)
점 2: (2.00, 4.00)
점 3: (3.00, 5.00)
점 4: (4.00, 4.00)
점 5: (5.00, 5.00)

상관 계수 해석:
상관 계수 값: 0.8528
강한 양의 상관관계

주요 개선 사항:

  1. interpretCorrelation() 함수 추가
  2. 상관 강도에 대한 자세한 설명 제공
  3. 상관관계를 다양한 수준으로 분류
  4. 제목 및 명확한 출력으로 사용자 인터페이스 개선

요약

이 실험에서는 C 언어로 피어슨 상관 계수를 계산하기 위해 쌍 (x, y) 데이터를 읽는 방법을 배웠습니다. 사용자는 쌍으로 된 숫자 데이터를 입력하고 추가 분석을 위해 저장할 수 있는 프로그램을 만들었습니다. 또한, 프로그램을 확장하여 공식을 사용하여 피어슨 상관 계수를 계산하기 위한 필요한 합계를 계산했습니다.

이 실험에서 다룬 주요 단계는 쌍 (x, y) 데이터를 읽고, 상관 공식에 필요한 합계를 계산하고, 최종 상관 계수를 출력하는 것입니다. 이러한 단계를 따르면 사용자의 C 프로그램에 피어슨 상관 계산을 구현할 수 있습니다.