[ create a new paste ] login | about

Link: http://codepad.org/vMdYlwYN    [ raw code | output | fork ]

mohit_at_codepad - C, pasted on Jun 13:
// Calculate the value of pi using Gauss-Legendre method
// http://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_algorithm
#include <stdio.h>
#include <float.h>
#include <math.h>

int main() {
  double a = 1, b = sqrt(2.0)/2, t = 0.25, p = 1.;
  double pi = 0.0625 * (a+b) * (a+b);
  int debug_counter = 0;
  double old_pi;
  do {
    float na;
    old_pi = pi;
    na = 0.5 * (a+b);
    b  = sqrt(a*b);
    t -= p * (a - na) * (a - na);
    p *= 2;
    a = na;
    pi = (a+b) * (a+b) / 4 / t;
    //printf("DEBUG:: Iteration %02d: %.*lf\n", ++debug_counter, DBL_DIG, old_pi);
  } while( fabs(pi - old_pi) > DBL_EPSILON );
  printf("pi = %.7lf\n", pi);
  return 0;
}


Output:
1
pi = 3.1415926


Create a new paste based on this one


Comments: