** UnhandledExceptionEventHandler :: OFFICIAL LC / CHATTER THREAD **
double approximate(int n) { int i; double inverse_n = 1/(double)n; //division is slow, so we can compute the inverse outside the loop double sum=0.0f; double denominator; for (i=1;i<n+1;i++) { denominator = 1+(i-0.5f)*(i-0.5f)*inverse_n*inverse_n; sum= sum+ 1/denominator; } double pi= sum*4*inverse_n; return pi; } int main() { const double min_err = 0.000001f; //10^-6 double approx = 4.0f; //property of midpoint rule implies we can't do worse than f(1)=3.2 int n_estimate = 1/sqrt((24*min_err)); //error estimate of trapezium rule(always underestimates) int n = n_estimate; int i =1; while (approx-M_PI> min_err) //don't need to use fabs(approx-PI), since this integral always overestimate { i=i*2; approx = approximate(n_estimate+i); //printf("approx = %.8lf\n",approx); } i =i/2; approx = 4.0f; while (approx-M_PI> min_err) //could use a binary search,but require additonal control flow { //the program is not computtionally intensive, so squential search is probably fine i=i+1; approx = approximate(n_estimate+i); //printf("approx = %.8lf\n",approx); } n = n+i; printf("n = %d\n",n); }
double approximate(int n) { int i; double inverse_n = 1/(double)n; //division is slow, so we can compute the inverse outside the loop double sum=0.0f; double denominator; for (i=1;i<n+1;i++) { denominator = 1+(i-0.5f)*(i-0.5f)*inverse_n*inverse_n; sum= sum+ 1/denominator; } double pi= sum*4*inverse_n; return pi; } int main() { const double min_err = 0.000001f; //10^-6 double approx = 4.0f; //property of midpoint rule implies we can't do worse than f(1)=3.2 int n_estimate = 1/sqrt((24*min_err)); //error estimate of trapezium rule(always underestimates) int n = n_estimate; int i =1; while (approx-M_PI> min_err) //don't need to use fabs(approx-PI), since this integral always overestimate { i=i*2; approx = approximate(n_estimate+i); //printf("approx = %.8lf\n",approx); } i =i/2; approx = 4.0f; while (approx-M_PI> min_err) //could use a binary search,but require additonal control flow { //the program is not computtionally intensive, so squential search is probably fine i=i+1; approx = approximate(n_estimate+i); //printf("approx = %.8lf\n",approx); } n = n+i; printf("n = %d\n",n); }