Difference between revisions of "Monte Carlo Calculation of Pi"
From WLCS
Line 11: | Line 11: | ||
# Create a variable for our '''numHits''' | # Create a variable for our '''numHits''' | ||
# Write a loop that runs N times | # Write a loop that runs N times | ||
− | ## Generate random numbers for '''x''' and '''y''' | + | ## Generate random numbers for '''x''' and '''y''' (from 0 to 1.0 by using '''random.random()''') |
## Use the distance formula to calculate the distance from (0, 0) to (x, y) | ## Use the distance formula to calculate the distance from (0, 0) to (x, y) | ||
## Increment (Increase by 1) '''numHits''' if the distance is less than 1 | ## Increment (Increase by 1) '''numHits''' if the distance is less than 1 |
Revision as of 14:31, 26 September 2013
Objective:
- To become well-learned in the way of the while loop
Resources:
Directions:
- Prompt the user for a number N (this will be our total number of test points
- Create a variable for our numHits
- Write a loop that runs N times
- Generate random numbers for x and y (from 0 to 1.0 by using random.random())
- Use the distance formula to calculate the distance from (0, 0) to (x, y)
- Increment (Increase by 1) numHits if the distance is less than 1
- Calculate an estimate of pi
- successProbability = numHits / N
- pi = successProbability / 4
- Print out your estimate of pi