Monte Carlo Calculation of Pi

From WLCS
Revision as of 13:09, 1 February 2019 by Admin (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Objective:

  • To become well-learned in the way of the while loop

Resources:

Directions:

  1. import random (at the top b/c you will be generating random numbers)
  2. Prompt the user for a number N (this will be our total number of test points)
  3. Create a variable for our numHits (this is *not* our loop counter)
  4. Write a loop that runs N times (you should use a loop counter variable like count and avoid using x because we will use x for something else)
    1. Generate random numbers for x and y between 0 and 1.0 by using random.random() (Note: this function does not need any parameters)
    2. Use the distance formula to calculate the distance from (0, 0) to (x, y)
    3. Increment (Increase by 1) numHits if the distance is less than 1
  5. Calculate an estimate of pi
    • successProbability = numHits / N
    • PI = successProbability * 4
  6. Print out your estimate of PI