Skip to content

Commit

Permalink
Added post-class assessment and example code for instructors
Browse files Browse the repository at this point in the history
  • Loading branch information
mikewallis committed Sep 16, 2015
1 parent 55f7143 commit 4d555eb
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
41 changes: 41 additions & 0 deletions profiling_pi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Profiling pi methods
# mw 20150916

import math
import random
import decimal

@profile
def montecarlo(maxIt):
ctr = 0
variance = 3.141
for i in range(maxIt):
if math.pow(random.random(), 2.0) + math.pow(random.random(), 2.0) <= 1.0:
ctr += 1
result = (4.0 * ctr / maxIt)
if abs(math.pi - result) <= variance:
variance = abs(math.pi - result)
cbest=result
print " Monte Carlo method: "+str(cbest)

@profile
def archie(prec):
decimal.getcontext().prec = prec
D=decimal.Decimal

eps = D(1)/D(10**prec)

x = D(4)
y = D(2)*D(2).sqrt()

ctr = D(0)
while x-y > eps:
xnew = 2*x*y/(x+y)
y = D(xnew*y).sqrt()
x = xnew
ctr +=1
print " Archimedes method: "+ str((x+y)/D(2))

montecarlo(1000000) # number of iterations for the monte carlo routine to run
archie(8) # level of precision, eg 8 decimal places
print " Python value of pi: "+str(math.pi)[:9] # the value of pi in math.pi
7 changes: 7 additions & 0 deletions python_profiler.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,10 @@ Line # Hits Time Per Hit % Time Line Contents
22 4 5 1.2 2.0 m=2*i+3
23 50 61 1.2 24.9 return [2]+[x for x in s if x]
```
#### Post-class assessment
1. Please write two programs that each use a different method for calculating pi (this could involve extra research), OR write one program that uses two methods.
2. Profile each method
3. Determine a metric for efficiency
4. Determine which method for pi is the most efficient in your example.

An example python script is given in `profiling_pi.py`

0 comments on commit 4d555eb

Please sign in to comment.