Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Use Monte Carlo Simulation to approximate pi by considering the percentage of po

ID: 655450 • Letter: U

Question

Use Monte Carlo Simulation to approximate pi by considering the percentage of points with coordinates (x,y) generated randomly by choosing x and y both between 0 and 1, inside the unit quarted circle

Q: X^2 + y^2 = 1, x>=0 y>=0

when the quarter circle is taken to be inside the square

S: 0<=x<=1 and 0<=y<=1

Use approximation pi/4 = area Q / area S.

Hint: Do the simulation 10000 times and then 100000. (meaning choose the value of x and y randomly 10000 times and then 100000 times all between 0 and 1. find out how many times the pair of (x,y) falls inside the Q and divide that by the total number of trials. Does the zccuracy of pi increase as the number of trials increase?)

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double pi(double tolerance)
{
          double x, y, val, error;
          unsigned long sampled = 0, hit = 0, i;

          do {
                                        for (i = 1000000; i; i--, sampled++) {
                               x = rand() / (RAND_MAX + 1.0);
                               y = rand() / (RAND_MAX + 1.0);
                               if (x * x + y * y < 1) hit ++;
                    }

                    val = (double) hit / sampled;
                    error = sqrt(val * (1 - val) / sampled) * 4;
                    val *= 4;
                     fprintf(stderr, "Pi = %f +/- %5.3e at %ldM samples. ",
                    val, error, sampled/1000000);
          } while (!hit || error > tolerance);

          return val;
}

int main()
{
          printf("Pi is %f ", pi(3e-4));

          return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at drjack9650@gmail.com
Chat Now And Get Quote