#include #include float direct_sum (int n, float summand); float recursive_sum (int n, float summand, const int base_case_threshold); /* * evaluate the sum directly */ float direct_sum (int n, float summand) { float sum = 0.0; for (int i = 1; i <= n; i++) { sum += summand; } return sum; } /* * evaluate the sum recursively. */ float recursive_sum (int n, float summand, const int base_case_threshold) { float sum; if (n < base_case_threshold) { /* * if we are below the base-case threshold then do the sum directly */ sum = direct_sum (n, summand); } else { /* * otherwise do the sum recursively by making two calls to * ourself with half the N value. note caution is needed if n is odd. */ int half_n = n / 2; sum = recursive_sum (half_n, summand, base_case_threshold) + recursive_sum (n - half_n, summand, base_case_threshold); } return sum; } #define NP 100 int main (void) { float x = (float) (M_PI * M_PI); double sc; int base_case_threshold = 100; int nmin = 1024, nmax = 1024*1024*16, n; float dsum_error, rsum_error; float summand, dsum, rsum; sc = exp(log (((double) nmax) / nmin) / (NP-1)); n = nmin; for (int i = 0; i < NP; i++) { summand = x / n; dsum = direct_sum (n, summand); dsum_error = (float) fabs ((dsum - x) / x); rsum = recursive_sum (n, summand, base_case_threshold); rsum_error = (float) fabs ((rsum - x) / x); printf ("%10d %20.14f %20.14g\n", n, dsum_error, rsum_error); n *= sc; } return 0; }