In: Computer Science
Make a program in C++ and write explanations. Monte-Carlo methods Calculating pi with Monte-Carlo method is NOT allowed.
// C code to approximate pi
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main()
{
/* initialize random numbers */
srand(time(NULL));
int iterations=0, index, count = 0;
double xcoordinate,ycoordinate;
double square_radius;
double approx_pi;
printf("Enter the number of iterations: ");
scanf("%d",&iterations);
for ( index=0; index<iterations; index++)
{
xcoordinate = (double)rand()/RAND_MAX;
ycoordinate = (double)rand()/RAND_MAX;
square_radius =
xcoordinate*xcoordinate+ycoordinate*ycoordinate;
if (square_radius<=1)
count++;
}
approx_pi=(double)count/iterations*4;
printf("Approximate value pf pi: %f\n",approx_pi);
return 0;
}
/*
output:
Enter the number of iterations: 100
Approximate value pf pi: 3.240000
Enter the number of iterations: 10000
Approximate value pf pi: 3.142800
Enter the number of iterations: 100000000
Approximate value pf pi: 3.141976
*/