[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: how to generate pi in c



owens@netptc.net <owens@netptc.net>:
>  
>  GIYF

Who?

>  http://www.dartmouth.edu/~rc/classes/soft_dev/C_simple_ex.html

(0) phreaque /home/keeling_ time pi 2000000000
# of trials= 2000000000 , estimate of pi is 3.14158

real    4m41.812s
user    4m29.736s
sys     0m0.055s

Thanks.  Fun to play with.  Around 2 billion is where it maxes out
both my AMD-64 and PIV-2.4GHz Pentium.  A couple of modifications
allow it to accept a command line parameter instead of asking for
iterations:

   ---------------------------------------------
/* ~/devl/kr/src/pi.c                            20Nov2010        */
/*                                                                */
/* Program to compute Pi using Monte Carlo methods                */
/*                                                                */
/* gcc -o $HOME/bin/pi $HOME/devl/kr/src/pi.c -lm -Wall           */
/*                                                                */
/* http://www.dartmouth.edu/~rc/classes/soft_dev/C_simple_ex.html */

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#define SEED 35791246

int main( int argc, char *argv[] ) {

     int niter=0;
     double x, y;
     int i, count=0; /* # of points in the 1st quadrant of unit circle */
     double z;
     double pi;

     if( argc > 1 ) {

          sscanf( argv[ 1 ], "%d", &niter);

     } else {
          printf( "Enter the number of iterations used to estimate pi: " );
          scanf( "%d", &niter );
     }

     /* initialize random numbers */
     srand( SEED );
     count=0;

     for ( i=0; i < niter; i++ ) {
          x = ( double ) rand()/RAND_MAX;
          y = ( double ) rand()/RAND_MAX;
          z = x*x+y*y;
          if( z <= 1 ) count++;
     }

     pi=( double ) count / niter * 4;
     printf( "# of trials= %d , estimate of pi is %g \n", niter, pi );

}
   ---------------------------------------------


-- 
Any technology distinguishable from magic is insufficiently advanced.
(*)                                             Linux Counter #80292
- -    http://www.faqs.org/rfcs/rfc1855.html    Please, don't Cc: me.


Reply to: