근사값 출력
이 마지막 단계에서는 π 근사 프로그램을 개선하여 결과를 출력하는 함수를 만들고 출력 형식을 개선합니다.
random_points.c 파일을 수정해 봅시다.
cd ~/project
nano random_points.c
새로운 출력 함수와 개선된 출력으로 코드를 업데이트합니다.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define NUM_POINTS 1000000
// 근사 결과를 출력하는 함수
void print_pi_approximation(int total_points, int points_inside_circle) {
double pi_approximation = 4.0 * points_inside_circle / total_points;
printf("π 근사 결과\n");
printf("=====================\n");
printf("생성된 총 점 개수: %d\n", total_points);
printf("사분원 내 점 개수: %d\n", points_inside_circle);
printf("근사 π 값: %.8f\n", pi_approximation);
printf("실제 π 값: %.8f\n", M_PI);
printf("절대 차이: %.8f\n", fabs(pi_approximation - M_PI));
printf("근사 정확도: %.4f%%\n",
(1 - fabs(pi_approximation - M_PI) / M_PI) * 100);
}
int main() {
// 난수 생성기를 초기화합니다.
srand(time(NULL));
int points_inside_circle = 0;
// 무작위 점을 생성하고 사분원 내 점의 개수를 셉니다.
for (int i = 0; i < NUM_POINTS; i++) {
double x = (double)rand() / RAND_MAX;
double y = (double)rand() / RAND_MAX;
// 점이 사분원 내에 있는지 확인합니다.
if (x*x + y*y <= 1.0) {
points_inside_circle++;
}
}
// 근사 결과를 출력합니다.
print_pi_approximation(NUM_POINTS, points_inside_circle);
return 0;
}
프로그램을 컴파일하고 실행합니다.
gcc random_points.c -o random_points -lm
./random_points
예시 출력:
π 근사 결과
=====================
생성된 총 점 개수: 1000000
사분원 내 점 개수: 785398
근사 π 값: 3.14159200
실제 π 값: 3.14159265
절대 차이: 0.00000065
근사 정확도: 99.9998%
주요 개선 사항:
- 전용 함수
print_pi_approximation()를 만들었습니다.
- 더 나은 정확도를 위해 점의 개수를 1,000,000 으로 늘렸습니다.
- 더 자세한 출력 형식을 추가했습니다.
- 근사 정확도 백분율을 포함했습니다.