{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Answers to exercises: 3_flowcontrol.ipynb" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2022-08-30T20:15:56.937640Z", "start_time": "2022-08-30T20:15:55.850889Z" } }, "outputs": [], "source": [ "# Import the usual stuff first\n", "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "sns.set_style('white')\n", "%matplotlib inline\n", "\n", "# We'll need this too\n", "import logomaker\n", "import os.path \n", "from scipy.signal import convolve" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This course will include a variety of exercises to increase your Python skills. Note that the knowledge needed to complete each exercise will NOT necessarily have been presented or discussed. If you find yourself at sea, **the first thing you should do is Google your question.** " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Before there were calculators, people had to compute numbers like $\\pi$ by hand. This was done by deriving an infinite series expression, then hand-computing the first $N$ terms using standard arithmetic. One way of computing $\\pi$ was the **Leibnitz series**:\n", "\n", "$$\\pi = 4 \\left(1 - \\frac{1}{3} + \\frac{1}{5} - \\frac{1}{7} + \\cdots \\right) = \\sum_{n=0}^\\infty 4 \\frac{(-1)^n}{2n+1}$$\n", "\n", "A different way of computing $\\pi$ was the **Madhava series**:\n", "\n", "$$ \\pi = \\sqrt{12} \\left( 1 - \\frac{1}{3 \\cdot 3} + \\frac{1}{5 \\cdot 3^2} - \\frac{1}{7 \\cdot 3^3} + \\cdots \\right) = \\sum_{n=0}^\\infty \\sqrt{12} \\frac{(-1)^n}{(2n+1)\\cdot 3^n} $$\n", "\n", "We will compare the accuracies of these series in two different ways." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**E3.1**: Using a `for` loop, estimate $\\pi$ using the first $10$ terms in both the Liebnitz and Madhava series. Which estimate is more accurate?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2021-09-01T12:41:07.269963Z", "start_time": "2021-09-01T12:41:07.261018Z" } }, "outputs": [], "source": [ "# Answer \n", "\n", "# Initialize both estimates of pi to zero\n", "pi_L = 0\n", "pi_M = 0\n", "\n", "# Iterate over n, each time adding the next term to each approximation\n", "for n in range(10):\n", " pi_L += 4 * (-1)**n / (2*n + 1)\n", " pi_M += np.sqrt(12) * (-1)**n / ((2*n+1) * 3**n)\n", " \n", "# Print the results\n", "print(f'pi_L = {pi_L:.15f}')\n", "print(f'pi_M = {pi_M:.15f}')\n", "print(f'pi = {np.pi:.15f}')\n", "print('The Madhava series is far more accurate')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**E3.2**: Write a function that computes the Leibnitz series for $\\pi$ to a specified number of terms. Include a docstring and checks to make sure the input is sane." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2021-09-01T12:41:07.800220Z", "start_time": "2021-09-01T12:41:07.790926Z" } }, "outputs": [], "source": [ "# Write function here \n", "\n", "def pi_leibnitz(N):\n", " \"\"\"\n", " Computes the Liebnitz series for pi to N terms. \n", " N must be an int >= 0.\n", " \"\"\"\n", " \n", " # Check input\n", " assert isinstance(N, int), 'N must be an integer'\n", " assert N >= 0, 'N must be positive'\n", " \n", " # Compute terms\n", " ns = np.arange(N)\n", " terms = 4*((-1)**ns / (2*ns+1))\n", " approx = terms.sum()\n", " \n", " # Return estimte to user\n", " return approx\n", "\n", "# To check that this is working\n", "for N in [1, 10, 100, 1000]:\n", " print(f'pi_leibnitz({N}) = {pi_leibnitz(N):.10f}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2021-09-01T12:41:08.018447Z", "start_time": "2021-09-01T12:41:07.971551Z" } }, "outputs": [], "source": [ "# Check that the docstring works\n", "pi_leibnitz?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2021-09-01T12:41:08.527270Z", "start_time": "2021-09-01T12:41:08.410019Z" } }, "outputs": [], "source": [ "# Check that crazy input is caught\n", "pi_leibnitz(.5)" ] }, { "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.9.15" }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 4 }