{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "*This notebook contains material for CBE 20258 Numerical and Statistical Analysis taught at the University of Notre Dame. (c) Professors Alexander Dowling, Ryan McClarren, and Yamil Colón. This collection of notebooks [cbe-xx258](https://ndcbe.github.io/cbe-xx258) is available [on Github](https://github.com/ndcbe/cbe-xx258).*\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "< [1.3 Flow Control and Pseudocode](https://ndcbe.github.io/cbe-xx258/01.03-Flow-control.html) | [Contents](toc.html) | [1.5 List, Dictionaries, and Enumeration](https://ndcbe.github.io/cbe-xx258/01.05-Lists-Dictionaries-Enumerate.html) >
"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# IMPORT DATA FILES USED BY THIS NOTEBOOK\n",
"import os, requests\n",
"\n",
"file_links = [(\"data/fifth_republic.txt\", \"https://ndcbe.github.io/cbe-xx258/data/fifth_republic.txt\"),\n",
" (\"data/hats.txt\", \"https://ndcbe.github.io/cbe-xx258/data/hats.txt\")]\n",
"\n",
"# This cell has been added by nbpages. Run this cell to download data files required for this notebook.\n",
"\n",
"for filepath, fileurl in file_links:\n",
" stem, filename = os.path.split(filepath)\n",
" if stem:\n",
" if not os.path.exists(stem):\n",
" os.mkdir(stem)\n",
" if not os.path.isfile(filepath):\n",
" with open(filepath, 'wb') as f:\n",
" response = requests.get(fileurl)\n",
" f.write(response.content)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "Z_7CzQztmUoo",
"nbpages": {
"level": 1,
"link": "[1.4 Functions, Scoping, and Other Fun Stuff](https://ndcbe.github.io/cbe-xx258/01.04-Functions-scoping.html#1.4-Functions,-Scoping,-and-Other-Fun-Stuff)",
"section": "1.4 Functions, Scoping, and Other Fun Stuff"
}
},
"source": [
"# 1.4 Functions, Scoping, and Other Fun Stuff\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 1,
"link": "[1.4 Functions, Scoping, and Other Fun Stuff](https://ndcbe.github.io/cbe-xx258/01.04-Functions-scoping.html#1.4-Functions,-Scoping,-and-Other-Fun-Stuff)",
"section": "1.4 Functions, Scoping, and Other Fun Stuff"
}
},
"source": [
"**Reference**: Chapter 3 of *Computational Nuclear Engineering and Radiological Science Using Python*, R. McClarren (2018) "
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 2,
"link": "[1.4.1 Learning Objectives](https://ndcbe.github.io/cbe-xx258/01.04-Functions-scoping.html#1.4.1-Learning-Objectives)",
"section": "1.4.1 Learning Objectives"
}
},
"source": [
"## 1.4.1 Learning Objectives\n",
"\n",
"After studying this notebook, completing the activities, and asking questions in class, you should be able to:"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "Vvv-zUXfmUop",
"nbpages": {
"level": 2,
"link": "[1.4.2 Functions](https://ndcbe.github.io/cbe-xx258/01.04-Functions-scoping.html#1.4.2-Functions)",
"section": "1.4.2 Functions"
}
},
"source": [
"## 1.4.2 Functions\n",
"\n",
"### Motivating Example"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "x5araXX7mUoq",
"nbpages": {
"level": 2,
"link": "[1.4.2 Functions](https://ndcbe.github.io/cbe-xx258/01.04-Functions-scoping.html#1.4.2-Functions)",
"section": "1.4.2 Functions"
}
},
"source": [
"Why use functions? We want to write, debug, and test code **once** and then **reuse** as much as possible.\n",
"\n",
"In a few class sessions, we'll formulate mass balances as linear systems and solve them using Python. But for now, let's just consider a problem you would expect to see in math class:\n",
"\n",
"We want to solve the linear system,\n",
"\n",
"$$\\mathrm{Eqn.~1}:\\quad 4.5 x + 3 y = 10.5\\\\\\mathrm{Eqn.~2}:\\quad 1.5 x + 3 y = 7.5.$$\n",
"\n",
"One way to do this is using Python as calculator. In the comments below, we walk through the steps."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 87
},
"colab_type": "code",
"executionInfo": {
"elapsed": 750,
"status": "ok",
"timestamp": 1548171075668,
"user": {
"displayName": "Alexander Dowling",
"photoUrl": "https://lh3.googleusercontent.com/-LChdQ2m5OQE/AAAAAAAAAAI/AAAAAAAAAA0/JeXJe4vQJ7M/s64/photo.jpg",
"userId": "00988067626794866502"
},
"user_tz": 300
},
"id": "9F-6X4lhmUos",
"nbpages": {
"level": 2,
"link": "[1.4.2 Functions](https://ndcbe.github.io/cbe-xx258/01.04-Functions-scoping.html#1.4.2-Functions)",
"section": "1.4.2 Functions"
},
"outputId": "44077880-5b15-46b6-a4a3-9d43943c2c98"
},
"outputs": [],
"source": [
"\"\"\"python code to solve \n",
"4.5 x + 3 y = 10.5\n",
"1.5 x + 3 y = 7.5\n",
"by solving the second equation for y first,\n",
"and then solving for x\"\"\"\n",
"#step 1 solve for y, multiply equation 2 by -3, \n",
"## and add to first equation\n",
"LHS_coefficient = -3*3 + 3 #the coefficient for y\n",
"RHS = -3*7.5 + 10.5 #the right-hand side\n",
"\n",
"print('LHS_coefficient:',LHS_coefficient)\n",
"print('RHS:',RHS)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 2,
"link": "[1.4.2 Functions](https://ndcbe.github.io/cbe-xx258/01.04-Functions-scoping.html#1.4.2-Functions)",
"section": "1.4.2 Functions"
}
},
"source": [
"Mathematical, we started by multiplying equation 2,\n",
"\n",
"$$1.5 x + 3 y = 7.5$$\n",
"\n",
"by -3,\n",
"\n",
"$$(-3) \\times 1.5 x + (-3) \\times 3 y = (-3) \\times 7.5$$\n",
"\n",
"\n",
"and then added this scaled equation 2 to equation 1, giving:\n",
"\n",
"$$(4.5 - 3 \\times 1.5) x + (3 - 3 \\times 3) y = 10.5 - 3 \\times 7.5$$\n",
"\n",
"Notice that our choice of scaling equation 2 by -3 means that the coefficient for x becomes zero after addition addition. The coefficient for $y$ is `LHS_coefficient` is our code. `RHS` is the right hand side of the new equation.\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"nbpages": {
"level": 2,
"link": "[1.4.2 Functions](https://ndcbe.github.io/cbe-xx258/01.04-Functions-scoping.html#1.4.2-Functions)",
"section": "1.4.2 Functions"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The solution to:\n",
"4.5 x + 3 y = 10.5\n",
"1.5 x + 3 y = 7.5\n",
" is x = 1.0 y= 2.0\n"
]
}
],
"source": [
"#now divide right-hand side by left-hand side coefficient\n",
"y = RHS / LHS_coefficient\n",
"#plug y into first equation\n",
"x = (10.5 - 3*y)/4.5 \n",
"#print the solution, note \\n produces a linebreak\n",
"print(\"The solution to:\\n4.5 x + 3 y = 10.5\\n1.5 x + 3 y = 7.5\\n is x =\",\n",
" x,\"y=\",y)"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "192rbx9dmUow",
"nbpages": {
"level": 2,
"link": "[1.4.2 Functions](https://ndcbe.github.io/cbe-xx258/01.04-Functions-scoping.html#1.4.2-Functions)",
"section": "1.4.2 Functions"
}
},
"source": [
"How to extend this code to another linear system?\n",
"\n",
"**Let's define a function** that will solve the system for (almost) any coefficients and right-hand side. \n",
"\n",
"I'll define such a function to solve $$a_1 x + b_1 y = c_1\\\\ a_2 x + b_2 y = c_2.$$"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbgrader": {
"grade": false,
"locked": false,
"solution": false
},
"nbpages": {
"level": 2,
"link": "[1.4.2 Functions](https://ndcbe.github.io/cbe-xx258/01.04-Functions-scoping.html#1.4.2-Functions)",
"section": "1.4.2 Functions"
}
},
"source": [
"
\n",
"def volume(radius):\n",
" \"\"\"compute volume of a sphere\n",
"\n",
" Args:\n",
" radius: float giving the radius of the sphere\n",
"\n",
" Returns:\n",
" volume of the sphere as a float\n",
" \"\"\"\n",
" return 4.0/3.0*math.pi*radius**3\n",
"\n",
"def surface_area(radius):\n",
" \"\"\"compute surface area of a sphere\n",
"\n",
" Args:\n",
" radius: float giving the radius of the sphere\n",
"\n",
" Returns:\n",
" surface area of the sphere as a float\n",
" \"\"\"\n",
" return 4.0*math.pi*radius**2\n",
"
"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "tlLecRQrmUp-",
"nbpages": {
"level": 2,
"link": "[1.4.5 Modules](https://ndcbe.github.io/cbe-xx258/01.04-Functions-scoping.html#1.4.5-Modules)",
"section": "1.4.5 Modules"
}
},
"source": [
"I can use the help function to tell me about the module:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 305
},
"colab_type": "code",
"executionInfo": {
"elapsed": 214,
"status": "error",
"timestamp": 1548342630031,
"user": {
"displayName": "Alexander Dowling",
"photoUrl": "https://lh3.googleusercontent.com/-LChdQ2m5OQE/AAAAAAAAAAI/AAAAAAAAAA0/JeXJe4vQJ7M/s64/photo.jpg",
"userId": "00988067626794866502"
},
"user_tz": 300
},
"id": "vLceeHInmUp-",
"nbpages": {
"level": 2,
"link": "[1.4.5 Modules](https://ndcbe.github.io/cbe-xx258/01.04-Functions-scoping.html#1.4.5-Modules)",
"section": "1.4.5 Modules"
},
"outputId": "4523bd79-84b2-4676-b141-ee0478b99e47"
},
"outputs": [
{
"ename": "ModuleNotFoundError",
"evalue": "No module named 'sphere'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m "
]
}
],
"metadata": {
"colab": {
"name": "L3-Functions-Scoping-Etc.ipynb",
"provenance": [],
"version": "0.3.2"
},
"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
}