codepad
[
create a new paste
]
login
|
about
Language:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
// 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; }
Private
[
?
]
Run code
Submit