home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
World of Shareware - Software Farm 2
/
wosw_2.zip
/
wosw_2
/
CPROG
/
PI-5WAYS.ZIP
/
CANNON.C
next >
Wrap
C/C++ Source or Header
|
1991-06-15
|
3KB
|
112 lines
/**************************************************************************/
/* Calculate π by "shooting a cannon" at a round pond of radius 1 */
/* 'inscribed' in a 2 x 2 square of land. */
/* This is a variation of the "Monte Carlo" method of simulation */
/* */
/* Note| Center of circle is at (1,1). Corners of land are: */
/* (0,0), (1,0), (1,1), (0,1). */
/* */
/* Mendel Cooper */
/* 3138 Foster Ave. */
/* Baltimore, MD 21224 */
/* */
/* 06/91 */
/* Source code placed in the public domain */
/**************************************************************************/
/* May need #include <math.h> */
/*********************************************************************/
/* GET_SEED */
/* Returns 4-digit random seed from BIOS time (up to 5959) */
/*********************************************************************/
int get_seed()
{
char *time, *gettime(),time$[5];
int j;
time = gettime();
*(time$) = *(time + 3);
*(time$ + 1) = *(time + 4);
*(time$ + 2) = *(time + 6);
*(time$ + 3) = *(time + 7);
*(time$ + 4) = '\0';
j = atoi(time$);
return (j);
}
/**********************************************************************/
/* GETRAND() */
/* Outputs random number (0.0 - 2.0) */
/**********************************************************************/
double getrand()
{
int random; /*number generated by rand() function*/
double scale_factor = 16384.0; /*scaling factor*/
double rand0_2; /*random number between 0.0 and 2.0 returned by fn*/
srand(get_seed()); /*seeds random generator*/
random = rand();
rand0_2 = (double)random / scale_factor;
return (rand0_2);
}
/**************************************************************************/
main()
{
double fabs(), sqrt(), getrand(), X, Y, Dx, Dy, distance, ratio, Pi;
int shots = 0, splashes = 0, thuds = 0;
clrscrn(); /* Clears screen. You may delete this line if error. */
while (shots < 32000) { /*integer value, still...*/
shots++;
X = getrand(); /*Generate X and Y coordinates*/
Y = getrand(); /* of shots */
/* Origin is at (1.0,1.0), remember */
Dx = fabs( 1 - X); /*find distance from origin*/
Dy = fabs( 1 - Y);
distance = sqrt( Dx*Dx + Dy*Dy); /* by Pythagorean Theorem */
if (distance <= 1.0)
{ splashes++; printf("SPLASH! "); }
else { thuds++; printf("THUD. "); }
printf("%5d splashes | %5d thuds ", splashes, thuds);
ratio = (double)splashes / (double)shots; /* Should be ≈ ¼π */
Pi = ratio * 4.0;
printf("At %5d shots ---- π ≈ %f. \n", shots, Pi);
}
}