Lab02: Functions¶
Brief Honor Code. Do the homework on your own. You may discuss ideas with your classmates, but DO NOT copy the solutions from someone else or the Internet. If stuck, discuss with TA.
1. (10 points)
Rewrite the following code into functional form using lambdas, map, filter and reduce.
In [43]:
n = 10
s = 10
for i in range(n):
if i % 2:
s |= i**2
s
Out[43]:
123
2. (10 points)
Rewrite the code above as a toolz
pipeline, using lambdas and
curried or partially applied functions as necessary.
3. (10 points)
Repeat the Buffon’s needle simulation from Lab01 as a function that
takes the number of needels n
as input and returns the estimate of
\(\pi\). The function should use numpy
and vectorization. What
is \(\pi\) for 1 million needles?
4. (20 points)
Simpsons rule is given by the follwoing approximation
- Write Simpsons rule as a function
simpsons(f, a, b, n=100)
where n is the number of equally spaced intervals froma
tob
. (10 points) - Use this function to estimate the probability mass of the standard normal distribution between -1 and 1. Implement the PDF of the standard normal distribution \(\psi(x)\) as a function. (10 points)
5. (50 points)
Write code to generate a plot similar to the following
using the explanation for generation of 1D Cellular Automata found
here.
You should only need to use standard Python, numpy
and
matplotllib
.
The input to the function making the plots should be a simple list of rules
rules = [30, 54, 60, 62, 90, 94, 102, 110, 122, 126,
150, 158, 182, 188, 190, 220, 222, 250]
make_plots(rules, niter, ncols)
You may, of course, write other helper functions to keep your code modular.