How to plot your results in python, using Gnuplot
|
Here's a graph of five estimates of π, as a function of R. See below
for my program.
See the theory page for a figure
showing the sort of theory I want you to create.
|
|
import random
def measure_pi( R , period=100 ) :
"""
Example:
>>> measure_pi( 100 )
is equivalent to asking 100 students to
toss coins (64 times, 32 times for x and 32 times for y)
and see if (x,y) is in the circle.
Every 'period' points, the current answer is recorded.
"""
answers= [] ; I = 0 ;
for r in range(R) :
x=random.random()
y=random.random()
if (x**2 + y**2 < 1.0) :
I += 1
pass
if ( ((r+1) % period)==0 ) or ( r + 1 == R ) :
this_answer = I * 4.0 / (r+1)
answers.append( [ r , this_answer ] )
pass
pass
print I * 4.0 / R
return answers
### Example of how to use measure_pi
Rmax = 1000000
a = measure_pi(Rmax)
### How to plot the results
from Numeric import *
import Gnuplot, Gnuplot.funcutils
# debug=1 prints gnuplot commands as they are run
g = Gnuplot.Gnuplot(debug=1, persist=1)
g.title('A simple example') # (optional)
g('set data style lines') # You can give gnuplot an arbitrary command
# example of how to plot a list of (x, y) pairs
# g.plot([[0,1.1], [1,5.8], [2,3.3], [3,4.2]])
g.plot(a)
#### if you want to wait here, include this line:
## raw_input('Please press return to continue...\n')
## Now run the program 4 more times
b = measure_pi(Rmax)
g.plot(a,b)
c = measure_pi(Rmax)
g.plot(a,b,c)
d = measure_pi(Rmax)
g.plot(a,b,c,d)
e = measure_pi(Rmax)
g.plot(a,b,c,d,e)
# how to get the x axis to be a logscale
g('set logscale x')
g('set xrange [90:1100000]') # set the xrange
g.replot()
g('set yrange [3.11:3.17]') # set the yrange
g.replot()