/* * Program to approximate pi using numerical integration, starting with initial * number of slices and repeating with increasing number of slices until * values converge (difference between successive estimates small). */ #include #include double estimate_pi(long slices); int main(void) { long slices; printf("enter starting number of slices:\n"); if ((scanf("%ld", &slices) != 1) || (slices <= 0)) { printf("not a positive number\n"); } double threshold; printf("enter convergence threshold:\n"); if ((scanf("%lf", &threshold) != 1) || (threshold <= 0)) { printf("not a positive number\n"); return 1; } double previous_estimate = 0; double estimate = 0; do { previous_estimate = estimate; estimate = estimate_pi(slices); printf("for %ld slices, estimated pi = %.15f\n", slices, estimate); slices *= 2; } while (fabs(estimate - previous_estimate) > threshold); return 0; } double estimate_pi(long slices) { double sum_of_heights = 0.0; double width_of_slice = 1.0/slices; for (int i = 0; i < slices; ++i) { /* height = 4/(1+x*x) at the midpoint */ double midpoint = (i + 0.5)*width_of_slice; sum_of_heights += 4/(1 + midpoint*midpoint); } double pi = sum_of_heights * width_of_slice; return pi; }