/* * Program to approximate pi using numerical integration, starting with initial * number of slices and repeating with increasing number of slices until * "convergence" (previous and current values "close"). */ #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; double threshold; printf("enter initial number of slices, threshold\n"); if (scanf("%ld %lf", &num_slices, &threshold) != 2) { printf("wrong format\n"); return 1; } double prev; double current = 0.0; do { prev = current; current = pi_approx(num_slices); printf("with %ld slices approximation is %.15f\n", num_slices, current); num_slices *= 2; } while (fabs(current-prev) > threshold); printf("difference from best available constant %g\n", fabs(current - 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; }