Department of Computer Science | Institute of Theoretical Computer Science | CADMO

Theory of Combinatorial Algorithms

Prof. Emo Welzl and Prof. Bernd Gärtner

// Prog: random_pi.cpp // compute approximation of pi using random numbers. #include #include int main() { std::cout << "Number of experiments =? "; unsigned int n; std::cin >> n; // the random number generator; we us use the generator ANSIC ifm::random ansic (1103515245u, 12345u, 2147483648u, 12345u); // the number of times a random point from [0,1)^2 ends up in // the circle with center (1/2, 1/2) and radius 1/2 unsigned int pi_counter = 0; for (int i = 0; i < n; ++i) { // draw point at random from [0,1)^2 double x = ansic(); double y = ansic(); // compute squared distance of (x,y) to center (1/2, 1/2) double d_sqr = (x-0.5) * (x-0.5) + (y-0.5) * (y-0.5); if (d_sqr <= 0.25) ++pi_counter; // (x,y) in circle } // compute approximation of pi std::cout << "Pi is approximately " << 4.0 * pi_counter / n << ".\n"; return 0; }