/* * Program to approximate pi using numerical integration. */ #include #include /* best known value of pi (surprisingly, no standard M_PI defined!) */ #define M_PI acos(-1.0) double pi_approx(long nslices); int main(void) { long num_slices; printf("enter number of slices\n"); if (scanf("%ld", &num_slices) != 1) { printf("not number\n"); return 1; } double pi = pi_approx(num_slices); /* .15f says print 15 digits after decimal point -- default is less */ printf("with %ld slices approximation is %.15f\n", num_slices, pi); printf("difference from best available constant %g\n", fabs(pi - M_PI)); return 0; } double pi_approx(long nslices) { double width = 1.0 / nslices; double sum = 0.0; /* compute heights of rectangles and add */ for ( int i = 0; i < nslices; ++i) { double mid = i*width + 0.5*width; double f_at_mid = 4.0/(1 + mid*mid); sum += f_at_mid; } /* area is sum of heights times width */ return sum * width; }