{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Homework 2\n",
"\n",
"Student's Name: PLEASE INSERT YOUR NAME HERE (DOUBLE CLICK THIS BOX TO EDIT.)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"__Directions:__ Add work to this notebook to solve the problems below. \n",
"\n",
"Check your work. I give some tests that should be passed if you get it correct.\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": "markdown",
"metadata": {},
"source": [
"### 1. A for Loop with Errors\n",
"Below, a program has been written for the task of adding all integers $i =1, 2,\\ldots ,10$ \n",
"and printing the final result. Fix the program.\n",
"\n",
"(This is Exercise 3.1 from LL.)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n",
"sum = Sum + x\n",
"print ’sum: ’, sum"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2. The range Function\n",
"Write a slightly different version of the program above. Now, the range\n",
"function should be used in the for loop header, and only the even numbers from\n",
"[2, 10] should be added. Also, the (only) statement within the loop should read \n",
"`sum = sum + i.`\n",
"\n",
"(This is Exercise 3.2 from LL)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3. Area of Rectangle Versus Circle\n",
"\n",
"Consider one circle and one rectangle. The circle has a radius $r = 10.6$. The\n",
"rectangle has sides $a$ and $b$, but only $a$ is known from the outset. Let $a = 1.3$\n",
"and write a program that uses a while loop to find the largest possible integer $b$ that\n",
"gives a rectangle area smaller than, but as close as possible to, the area of the circle.\n",
"Run the program and confirm that it gives the right answer (which is $b = 271$).\n",
"\n",
"(This is Exercise 3.6 from LL.)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 4. Frequency of Random Numbers\n",
"Write a function named `dice` that takes a positive integer $N$ as input and then draws $N$ random\n",
"integers from the interval $[1, 6]$. In the function, count how many of the numbers,\n",
"$M$, that equal $6$ and print out the fraction $M/N$. Also, print all the random numbers\n",
"to the screen so that you can check for yourself that the counting is correct. Run the\n",
"program with a small value for $N$ (e.g., $N = 10$) to confirm that it works as intended.\n",
"\n",
"Hint: After running `import random` a random integer $x$ in $[1, 6]$ can be generated by `x = random.randint(1,6)`.\n",
"\n",
"(This is Exercise 3.7 from LL)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 5. Evaluating a series\n",
"\n",
"Write a computer program to “sum” the series \n",
"$$\\sum_{k=1}^\\infty \\frac{1}{2^k-1} = \\frac{1}{2-1} + \\frac{1}{4-1} + \\frac{1}{8-1} + \\ldots$$\n",
"stopping when\n",
"* all subsequent terms are zero to four decimal places, and\n",
"* two successive “sums” are equal to five decimal places.\n",
"Store the result in the variable `series_sum`.\n",
"\n",
"(Hints: Use Python floats. The number $x$ is zero to four decimal places if $x < 0.5 \\cdot 10^{-4}$. The numbers $x$ and $y$ are equal to five decimal places if $|x-y|<0.5 \\cdot 10^{-5}$.)\n",
"\n",
"This problem is based on problem 4 from chapter 2 of TAK."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following test should be satisfied by your answer. You will know if the test is passed if no error is printed."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"assert type(series_sum) == float, \"Error: 'series_sum' should be a float.\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 6. Ternary to int\n",
"\n",
"Write a function named `ternary_to_int` which takes as input a string consisting only of elements of $\\{0,1,2\\}$ giving the ternary expansion of a positive number and produces the integer.\n",
"\n",
"*Hints:* \n",
"* You can tell the number of characters in a string `s` with the command `len(s)`. \n",
"* You can get the $k$-th character with `s[k]`. A trick to get the $j$-th character from the end is to type `s[-j]`. In particular the first character is always `s[0]` and the last character is always `s[-1]`. \n",
"* You can convert a string `s` to an integer using `int(s)`. This works for single characters for instance.\n",
"* You can get the substring of `s` not including the first character using `s[1:]` and the substring not including the last character using `s[:-1]`. These are examples of string *slices*, which are covered in the [Python tutorial](https://docs.python.org/3/tutorial/introduction.html#strings) and in LL § 2.3.5. (The notion of slices works for strings, numpy arrays, lists and tuples.)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"*Testing:*\n",
"To test that your program works as expected, I copyied in the `ternary` function from the `Number Representations` notebook. This function converts an integer $n$ into a ternary string. Your function should satisfy \n",
"`ternary_to_int(ternary(n))==n`\n",
"for every positive integer n.\n",
"\n",
"The following loop carries this test out for the first $n=1$ to $100$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def ternary(n):\n",
" # Below we peform sanity checks on the input.\n",
" assert type(n) == int, 'n must be an integer'\n",
" assert n>0, 'n must be a positive integer.'\n",
"\n",
" rep = '' # This will store the ternary representation.\n",
" while n != 0:\n",
" trit = n % 3\n",
" rep = str(trit) + rep # add the new trit on the left.\n",
" n = n // 3 # Update the value of n.\n",
" return rep\n",
"\n",
"for n in range(1,101):\n",
" tern = ternary(n)\n",
" out = ternary_to_int(tern)\n",
" assert out == n, (\"Error: Output of `ternary_to_int('{}')` \" + \\\n",
" \"should be {}, but was {}.\").format(tern, n, out)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 7. Exact comparisons\n",
"\n",
"Let $r=\\sqrt[5]{2}$ be the $5$-th root of $2$. Write a function `compare_to_fraction(p,q)` which returns `True` if $r < \\frac{p}{q}$ and returns `False` if $r > \\frac{p}{q}$. \n",
"\n",
"You should use the interval arithmetic package in `mpmath`, and repeatedly increase the precision."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following assertion tests will be passed by a correct answer (Nothing happening is good!)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"assert compare_to_fraction(309, 269), \"Error, 'compare_to_fraction(309, 269)' should return True.\"\n",
"assert not compare_to_fraction(7810, 6799), \"Error, 'compare_to_fraction(7810, 6799)' should return False.\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 8. Computing digits.\n",
"\n",
"Compute the $20$ most significant digits of $\\pi^3$. Store the answer as a **string** in the variable `pi_cubed`. The last digit should be rounded (and so may not really be the $20$th digit). (Rounding is done automatically by the `nstr` function.)\n",
"\n",
"Include code that carries out this calculation."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following tests should be passed:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"assert type(pi_cubed) == str, \"Error: pi_cubed should be a string.\"\n",
"assert len(pi_cubed) == 21, \"Error: pi_cubed should have 20 significant digits.\"\n",
"# Note that the decimal point means that there will be one more character than "
]
}
],
"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
}