{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Homework 10\n",
"\n",
"Student's Name: PLEASE INSERT YOUR NAME HERE"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"__Directions:__ Add work to this notebook to solve the problems below. Some other cells have been included which are important for testing your work and should give you some feeback.\n",
"\n",
"Check your work.\n",
"\n",
"**Your notebook should run without printing errors and without user input. If this is not the case, points may be deducted from your grade.**\n",
"\n",
"Problem Sources:\n",
"* __LL__: *Programming for Computations - Python* by Svein Linge and Hans Petter Langtangen, 2nd edition.\n",
"* __L__: *A Primer on Scientific Programming with Python* by Hans Petter Langtangen, 2nd edition.\n",
"* __TAK__: *Applied Scientific Computing With Python* by Peter R. Turner, Thomas Arildsen, and Kathleen Kavanagh."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Standard imports\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import math as m\n",
"from mpmath import mp, iv\n",
"from scipy import linalg\n",
"\n",
"from numpy import random\n",
"\n",
"import random as random_number"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. Coins that land on their edge\n",
"\n",
"According to an [authorative youtube video](https://www.youtube.com/watch?v=M0I-xm7iCBU) a nickel has a $1/6000$ chance of landing on its edge. Write a function `nickel_flip()` that takes no inputs and returns one of three strings, \"Edge\", \"Heads\" and \"Tails\". The function should return \"Edge\" with probability $1/6000$ and return \"Heads\" and Tails\" with equal probability."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. Video game character's position"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A video game character lives in a $2$-dimensional integer lattice. That is, his coordinates are always a pair of integers $(x, y)$. He can move in the four compass directions one unit at a time.\n",
"\n",
"Write a class `Position` whose initialization method takes two parameters (in addition to `self`), the initial x-coordinate `x0` and the initial y-coordinate `y0`. Both should be integers. If `p` is a `Position` object, it should have the following methods:\n",
"* `p.north()` should increase the character's y-coordinate by one.\n",
"* `p.east()` should increase the character's x-coordinate by one.\n",
"* `p.south()` should decrease the character's y-coordinate by one.\n",
"* `p.west()` should decrease the character's x-coordinate by one.\n",
"* `p.beam(xb, yb)` should move the character directly to position `(xb, yb)`\n",
"* `p.x()` should return the characters x-coordinate.\n",
"* `p.y()` should return the characters y-coordinate.\n",
"* `p.coordinates()` should return the character's coordinates as a pair."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Test\n",
"p = Position(3, 5) # Start at position (3,5)\n",
"assert p.x() == 3\n",
"assert p.y() == 5\n",
"\n",
"p.south()\n",
"assert p.x() == 3\n",
"assert p.y() == 4\n",
"\n",
"p.west()\n",
"p.south()\n",
"assert p.coordinates() == (2, 3)\n",
"\n",
"p.beam(-2, 3)\n",
"p.north()\n",
"p.east()\n",
"assert p.coordinates() == (-1, 4)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. Keeping track of statistical data\n",
"\n",
"Write a class named `StatisticsTracker` which keeps track of statistical quantities related to real number measurements. No data should be passed to the initializer of the class. A `StatisticalTracker` object `st` should have the following methods available:\n",
"* `st.number()` should return the number of measurements received so far. (This should be a non-negative integer.)\n",
"* `st.mean()` should return the mean of the measurements received so far.\n",
"* `st.variance()` should return the variance of the measurements received so far.\n",
"* `st.new_measurement(x)` should update the internal variables of the class so that the quantities returned by the above methods are correct when adding the float `x` to the prior received data set. This method should return nothing.\n",
"\n",
"**Constraint:** You are not to store all the measurements received. Instead just store quantities necessary to keep track of the statistical quantities. Some hints are below.\n",
"\n",
"To keep track of the number of measurements, your class should devote a variable to keeping count of the number of measurements received.\n",
"\n",
"Recall that the mean of measurements $x_0, \\ldots, x_{n-1}$ is \n",
"$$\\mu = \\frac{1}{n} \\sum_{i=0}^{n-1} x_i.$$\n",
"The number $n$ is the total number of measurements. So, it also makes sense to keep track of the sum of the measurements.\n",
"\n",
"The variance should be computed by assuming all measurements made are equally likely. Thus the variance is given by the formula\n",
"$$Var = \\frac{1}{n} \\sum_{i=0}^{n-1} (x_i - \\mu)^2.$$\n",
"Since the mean $\\mu$ will change as more data is received, it is best to treat $\\mu$ as an unknown variable. Expanding the above formula we see:\n",
"$$Var = \n",
"\\frac{1}{n} \\left(\\sum_{i=0}^{n-1} x_i^2\\right) - \\frac{2 \\mu}{n}\\left(\\sum_{i=0}^{n-1} x_i\\right) + \\mu^2.$$\n",
"Thus it also makes sense to keep track of the sums of the squares of the measurements."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Test\n",
"st = StatisticsTracker()\n",
"assert st.number() == 0, \"The number of tests should be 0.\"\n",
"\n",
"st.new_measurement(5.0) # Add one measurement of 5.0\n",
"assert st.number() == 1, \"The number of tests should be 1.\"\n",
"assert st.mean() == 5.0, \"The mean should be 5.\"\n",
"assert st.variance() == 0.0, \"The variance should be 0.\"\n",
"\n",
"st.new_measurement(1.0) # Add a second measurement of 1.0\n",
"assert st.number() == 2, \"The number of tests should be 2.\"\n",
"assert st.mean() == 3.0, \"The mean should be 3.\"\n",
"assert st.variance() == 4.0, \"The variance should be 2.\"\n",
"\n",
"st.new_measurement(7.0) # Add a third measurement of 7.0\n",
"st.new_measurement(-4.0) # Add a fourth measurement of -4.0\n",
"assert st.number() == 4, \"The number of tests should be 2.\"\n",
"assert st.mean() == 2.25, \"The mean should be 2.25.\"\n",
"assert st.variance() == 17.6875, \"The variance should be 17.6875.\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. Taylor Series\n",
"\n",
"Write a class `TaylorSeries` so that the initializer of a `TaylorSeries` object takes two parameters, a coefficient function `c` mapping degrees (non-negative integers) to coefficients (floating point real numbers) and a center `x0`. The initialized object should represent the Taylor Series (expressed as a function of $x$):\n",
"$$\\sum_{d=0}^{+\\infty} c_d \\cdot (x - x_0)^d.$$\n",
"(Here we have used $c_d$ to represent `c(d)` and $x_0$ for `x0`.)\n",
"\n",
"A `TaylorSeries` object `ts` should have the following methods:\n",
"* `ts.center()` should return the center $x_0$.\n",
"* `ts.coefficient(d)` should return the coefficient of the degree $d$ term. That is, this function should return $c_d$ in the expression above.\n",
"* `ts.partial_sum(x,N)` should return the finite sum \n",
"$$\\sum_{d=0}^{N} c_d \\cdot (x - x_0)^d.$$\n",
"* `ts.derivative()` should return the derivative of this Taylor Series as a `TaylorSeries`. The derivative of the series is \n",
"$$\\sum_{d=0}^{+\\infty} (d+1) c_{d+1} \\cdot (x - x_0)^d.$$\n",
"\n",
"*Remark:* To define a derivative you should first define a coefficient function for the derivative series using currying. Then you can pass that new function to the `TaylorSeries` initializer.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Test\n",
"\n",
"# Construct the exponential function\n",
"c = lambda d: 1.0/m.factorial(d)\n",
"ts = TaylorSeries(c, 0)\n",
"\n",
"assert ts.partial_sum(0, 10) == 1.0\n",
"assert abs( ts.partial_sum(1.0, 15) - m.e ) < 10**-10, \\\n",
" \"ts.partial_sum(1.0, 15) should be close to e.\"\n",
"assert abs( ts.partial_sum(-1.0, 15) - 1/m.e ) < 10**-10, \\\n",
" \"ts.partial_sum(-1.0, 15) should be close to 1/e.\"\n",
"\n",
"# The derivative should also be the exponential function\n",
"der = ts.derivative()\n",
"\n",
"for d in range(10):\n",
" assert abs( der.coefficient(d) * m.factorial(d) - 1) < 10**-8, \\\n",
" \"The coefficient of der of degree {} is wrong.\".format(d)\n",
"\n",
"# Same checks as above.\n",
"assert der.partial_sum(0, 10) == 1.0\n",
"assert abs( der.partial_sum(1.0, 15) - m.e ) < 10**-10, \\\n",
" \"der.partial_sum(1.0, 15) should be close to e.\"\n",
"assert abs( der.partial_sum(-1.0, 15) - 1/m.e ) < 10**-10, \\\n",
" \"der.partial_sum(-1.0, 15) should be close to 1/e.\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 5. Random coefficients\n",
"\n",
"We'd like to construct a random function using Taylor series. To define a function in terms of Taylor series you just need to determine the coefficients. We'll choose the coefficients $c_d$ at uniformly from the interval $[\\frac{-1}{d!}, \\frac{1}{d!}]$. (This seems like a weird choice but guarantees that every derivative $f^{(n)}(x_0)$ is taken at random from $[-1,1]$. \n",
"\n",
"The following is a first attempt:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def random_coef(d):\n",
" bound = 1 / m.factorial(d)\n",
" return 2*bound*np.random.random_sample() - bound"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Unfortunately it doesn't work as the following plot demonstrates."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ts = TaylorSeries(random_coef, 0)\n",
"x = np.linspace(-5,5,1000)\n",
"y = [ts.partial_sum(val, 20) for val in x]\n",
"plt.plot(x,y)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What is happening is that every time the `TaylorSeries` object needs a coefficient, it calls `random_coef`. Each time this occurs it generates a new random number. But the coefficicient of degree `d` should be a constant. Observe:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"c3 = random_coef(3)\n",
"print(\"The coeficient of degree 3 is {}.\".format(c3))\n",
"c3 = random_coef(3)\n",
"print(\"The coeficient of degree 3 is {}.\".format(c3))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To fix this, we will create a function class that *caches* (stores) coefficients that it has already selected.\n",
"\n",
"Construct a class `RandomCoefficients` whose initializer takes no input. An object `rc` of type `RandomCoefficients` should have a `__call__` method so that `rc(d)` returns a random number between $\\frac{-1}{d!}$ and $\\frac{1}{d!}$. The call method should return the same random number whenever called with the same value of `d`.\n",
"\n",
"*Suggestion:* You might want to have a `RandomCoefficients` store a dictionary. When `rc(d)` is called for the first time with input `d`, the random number should be computed and stored as the image of `d` under the dictionary. Then when `rc(d)` is called a second time, the number should be restored from the dictionary and returned."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Test\n",
"\n",
"rc = RandomCoefficients()\n",
"val = rc(0)\n",
"assert -1 <= val <= 1\n",
"assert val == rc(0), \"The return value of rc(0) has changed.\"\n",
"\n",
"val = rc(2)\n",
"assert -1/2 <= val <= 1/2\n",
"assert val == rc(2), \"The return value of rc(2) has changed.\"\n",
"\n",
"assert val != rc(1), \"The return value of rc(1) should differ from rc(2).\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 6. Random Functions\n",
"\n",
"Use objects created by the `RandomCoefficients` class to create some random functions. Experiment with plotting these functions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}