/* * Program to approximate pi using numerical integration. */ #include double estimate_pi(long slices); int main(void) { long slices; printf("enter number of slices:\n"); if ((scanf("%ld", &slices) != 1) || (slices <= 0)) { printf("not a positive number\n"); return 1; } double pi = estimate_pi(slices); /* .15f says print 15 digits after decimal point -- default is less */ printf("for %ld slices, estimated pi = %.15f\n", slices, pi); return 0; } double estimate_pi(long slices) { double sum_of_heights = 0.0; double width_of_slice = 1.0/slices; for (long 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; }