//============================================================================ // Name : serial_pi_calc.c // Author : Morteza Zakeri // Version : 1.0.0 // Copyright : All right received. // Description : SERIAL PI CACULATION in C, Ansi-style //============================================================================ #include #include #include // include rand function #define sqr(x) ((x)*(x)) using namespace std; double cal_pi_serial(int darts) { double x_coord, /* x coordinate, between -1 and 1 */ y_coord, /* y coordinate, between -1 and 1 */ pi, /* pi */ r; /* random number scaled between 0 and 1 */ int score, /* number of darts that hit circle */ n; score = 0; for (n = 1; n <= darts; n++) { /* generate random numbers for x and y coordinates */ r = (double)rand() / (double)RAND_MAX; x_coord = (2.0 * r) - 1.0; r = (double)rand() / (double)RAND_MAX; y_coord = (2.0 * r) - 1.0; /* if dart lands in circle, increment score */ if ((sqr(x_coord) + sqr(y_coord)) <= 1.0) score++; } /* calculate pi */ pi = 4.0 * (double)score / (double)darts; return(pi); } #define DARTS 100000 #define ROUNDS 1000 int main() { double pi = 0; /* average of pi after "darts" is thrown */ double pi_avg = 0; /* average pi value for all iterations */ srandom (5); /* seed the random number generator */ for (int i = 0; i < ROUNDS; i++) { /* Perform pi calculation on serial processor */ pi = cal_pi_serial(DARTS); pi_avg = ((pi_avg * i) + pi) / (i + 1); //printf(" After %3d throws, average value of pi = %10.8f\n", (DARTS * (i + 1)), avepi); } printf(" Final PI = %10.8f\n", pi_avg); printf("\nReal value of PI: 3.1415926535897 \n"); return 0; }