//===================================================== file = findPi.c ===== //= Classic Monte Carlo simulation to estimate value of pi = //=========================================================================== //= Notes: = //= 1) This Monte Carlo simulation estimate pi by "throwing darts" at = //= a quarter circle of radius = 1 contained within a square of = //= side lenfth = 1. The area of the quarter circle is pi/4 and the = //= are of the square is 1. The percentage of darts that fall = //= inside the circle is used to estimate pi. = //= 2) The value of pi is 3.1415926535 to 10 places = //= 3) Must manually set NUM_ITER in the #define = //=-------------------------------------------------------------------------= //= Example execution: (NUM_ITER = 100000) = //= = //= *** BEGIN SIMULATION *** = //= ------------------------------------------------------------- = //= -- *** Results from Monte Carlo pi estimator *** -- = //= ------------------------------------------------------------- = //= - Number of iterations = 100000 = //= ------------------------------------------------------------- = //= - Estimated pi = 3.141120 = //= ------------------------------------------------------------- = //= *** END SIMULATION *** = //=-------------------------------------------------------------------------= //= Build: bcc32 findPi.c = //=-------------------------------------------------------------------------= //= Execute: findPi = //=-------------------------------------------------------------------------= //= Author: Ken Christensen = //= University of South Florida = //= WWW: http://www.csee.usf.edu/~christen = //= Email: christen@csee.usf.edu = //=-------------------------------------------------------------------------= //= History: KJC (03/29/09) - Genesis = //= KJC (06/08/09) - Some minor clean-up = //=========================================================================== //----- Include files ------------------------------------------------------- #include // Needed for printf() #include // Needed for pow() and sqrt() //----- Defines ------------------------------------------------------------- #define NUM_ITER 100000 // Number of iterations to run //----- Function prototypes ------------------------------------------------- double rand_val(int seed); // RNG for uniform(0.0, 1.0) from Jain //=========================================================================== //= Main program = //=========================================================================== int main() { double x, y; // X and Y values double len; // Length from (0,0) of X,Y point double hitCount; // Count of hits within the quarter circle double pi_est; // Estimated pi int i; // Loop counter // Output banner printf("*** BEGIN SIMULATION *** \n"); // Seed the RNG and initialize hitCount to zero rand_val(1); hitCount = 0.0; // Do for NUM_ITER iterations for (i=0; i 0) x = x_new; else x = x_new + m; // Return a random value between 0.0 and 1.0 return((double) x / m); }