/* * estimate pi using numerical integration * input is number of steps */ #include #include #include #include /* copied from not-strictly-standard part of math.h */ #define M_PI 3.14159265358979323846 double estimate_pi(int steps); int main(void) { int steps; printf("how many steps? maximum %d\n", INT_MAX); if ((scanf("%d", &steps) != 1) || (steps <= 0)) { printf("invalid input\n"); return EXIT_FAILURE; } double pi = estimate_pi(steps); printf("results with %d steps:\n", steps); printf("computed pi = %g (%17.15f)\n",pi, pi); printf("difference between computed pi and math.h M_PI = %g\n", fabs(pi - M_PI)); return EXIT_SUCCESS; } /* returns result of computation with "steps" steps */ double estimate_pi(int steps) { double sum = 0.0; double width = 1.0 / (double) steps; /* * we want to add up areas of rectangles: * width of each is given above * height of each is function value at midpoint * we can factor out width and multiply after computing sum of heights */ for (int i = 0 ; i < steps; ++i) { /* midpoint */ double x = (i+0.5)*width; sum += 4.0/(1.0+x*x); } return width * sum; }