April 6th, 2013, 10:55 AM

I don't know how to use Python... Help me!
I have NO IDEA how to use Python. Best answer if you write the full program! Please help me please please please ):
Accept / Reject Monte Carlo
Part I:
Goal:
Write a python program that will:
1. define a function for a specific probability density function f(x),
2. define a function that will sample from f(x) using the accept/reject Monte Carlo
algorithm,
3. make a histogram of the samples and compare to f(x).
Recall the accept / reject algorithm is:
I. generate a uniformly random value of x (in its range)
II. generate a uniformly random value y between [0,fmax], where fmax is some number
that is always larger than f(x)  ideally, it’s exactly the maximum of f(x).
III. if y < f(x) then accept x, else reject x.
By repeating this N times, this algorithm will produce a set of accepted x’s, written {xi} ,
so that that the normalized histogram looks like f(x). The ratio of the number of
accepted x’s to the number of trials (N) is the “acceptance efficiency” or “acceptance
probability”. You can think of an accepted value of x as a measurement, and the {xi} as
a set of measurements from repeated experiments.
Instructions
1. choose f(x) = x for x in the range [1,1],
2. define these python functions:
•“def f(x):” that returns the absolute value of x.
•“def acceptReject(N):” that returns a list of accepted {xi} using the accept / reject
algorithm
•“def makePlots():” that will for N=100, 1,000, and 100,000 do the following: a) call
acceptReject(N), b) calculate the acceptance efficiency, c) calculate the mean and
standard deviation for the {xi} , d) make a normalized histogram of {xi}, and e)
overlay the function f(x).
3. print out your python program
4. print out plots for N=100, 1,000, and 100,000.
5. note the mean, standard deviation, and acceptance efficiency for your three plots.
Extra Credit:
Do the same thing for a different f(x).
Part II:
Modify your acceptReject(N) function so that it always returns N accepted x values.
Hint: replace the “for i in range(N):” loop with a “while len(accepted) < N:” loop.
April 6th, 2013, 11:29 AM
