{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"# Ch.1: Computing with formulas\n",
"\n",
" **Hans Petter Langtangen**, Simula Research Laboratory and University of Oslo, Dept. of Informatics\n",
"\n",
"Date: **Aug 21, 2016**\n",
"\n",
"## Why program?\n",
"\n",
"> *Everybody in this country should learn how to program a computer... because it teaches you how to think*. Steve Jobs, 1955-2011.\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## The teaching strategy is example-based\n",
"\n",
" * Present a case (example)\n",
"\n",
" * Present the complete program\n",
"\n",
" * Dissect and discuss every line\n",
"\n",
" * Simulate programs by hand (be the computer!)\n",
"\n",
"\n",
"\n",
"## The learning strategy is about doing exercises\n",
"\n",
" * Study and try to understand examples\n",
"\n",
" * Program a lot!\n",
"\n",
" * This course has many compulsory exercises\n",
"\n",
" * The course curriculum is defined through exercises\n",
"\n",
"\n",
"\n",
"## Chapter 1 is about evaluating formulas\n",
"\n",
"**Why?**\n",
"\n",
" * Everybody understands the problem\n",
"\n",
" * Many fundamental concepts are introduced\n",
"\n",
" * variables\n",
"\n",
" * arithmetic expressions\n",
"\n",
" * objects\n",
"\n",
" * printing text and numbers\n",
"\n",
"\n",
"\n",
"## Formulas and arithmetics are fundamental...\n",
"\n",
"A physicist, a biologist and a mathematician were at a cafe when across the street two people entered a house. Moments later three people came out. The physicist said, \"Hmm, that must be a measurement error.\" The biologist wondered, \"It must be reproduction!\" And the mathematician said, \"If someone goes into the house, it will be empty again.\"\n",
"\n",
"\n",
"\n",
"## Evaluating a mathematical formula\n",
"\n",
"**Height of a ball in vertical motion.**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"y(t) = v_0t- \\frac{1}{2}gt^2\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where\n",
"\n",
" * $y$ is the height (position) as function of time $t$\n",
"\n",
" * $v_0$ is the initial velocity at $t=0$\n",
"\n",
" * $g$ is the acceleration of gravity\n",
"\n",
"Task: given $v_0$, $g$ and $t$, compute $y$.\n",
"\n",
"\n",
"\n",
"## Use a calculator? A program is much more powerful!\n",
"\n",
"**What is a program?**\n",
"\n",
"A sequence of instructions to the computer, written in a programming language, somewhat like English, but very much simpler - and very much stricter.\n",
"\n",
"\n",
"\n",
"This course teaches the Python language.\n",
"\n",
"\n",
"\n",
"**Our first example program:**\n",
"\n",
"Evaluate $y(t) = v_0t- \\frac{1}{2}gt^2$ for $v_0=5$, $g=9.81$ and $t=0.6$:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"y = 5\\cdot 0.6 - \\frac{1}{2}\\cdot 9.81 \\cdot 0.6^2\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The complete Python program:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print 5*0.6 - 0.5*9.81*0.6**2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## How to write and run the program\n",
"\n",
" * A program is plain text, written in a *plain text editor*\n",
"\n",
" * Use Gedit, Emacs, Vim, Spyder, or IDLE (*not* MS Word!)\n",
"\n",
"**Step 1.** Write the program in a text editor, here the line"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print 5*0.6 - 0.5*9.81*0.6**2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Step 2.**\n",
"Save the program to a file (say) `ball1.py`.\n",
"(`.py` denotes Python.)\n",
"\n",
"**Step 3.**\n",
"Move to a terminal window and go to the folder containing the program file.\n",
"\n",
"**Step 4.** Run the program:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" Terminal> python ball1.py\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The program prints out `1.2342` in the terminal window.\n",
"\n",
"\n",
"\n",
"## In this course we probably use computers differently from what you are used to\n",
"\n",
" * When you use a computer, you always run some programs\n",
"\n",
" * The computer cannot do anything without being precisely told what to do, and humans write and use programs to tell the computer what to do\n",
"\n",
" * Most people are used to double-click on a symbol to run a program - in this course we give commands in a terminal window because that is more efficient if you work intensively with programming\n",
"\n",
" * Hard math problems suddenly become straightforward by writing programs\n",
"\n",
"\n",
"\n",
"## A short program can calculate any integral\n",
"\n",
"You cannot calculate this integral by hand:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\int_{-\\infty}^1 e^{-x^2}dx{\\thinspace .}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A little program can compute this and \"all\" other integrals:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from numpy import *\n",
"\n",
"def integrate(f, a, b, n=100):\n",
" \"\"\"\n",
" Integrate f from a to b,\n",
" using the Trapezoidal rule with n intervals.\n",
" \"\"\"\n",
" x = linspace(a, b, n+1) # Coordinates of the intervals\n",
" h = x[1] - x[0] # Interval spacing\n",
" I = h*(sum(f(x)) - 0.5*(f(a) + f(b)))\n",
" return I\n",
"\n",
"# Define my special integrand\n",
"def my_function(x):\n",
" return exp(-x**2)\n",
"\n",
"minus_infinity = -20 # Approximation of minus infinity\n",
"I = integrate(my_function, minus_infinity, 1, n=1000)\n",
"print 'Value of integral:', I"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**The program computes an approximation with error $10^{-12}$ within 0.1 s** ($n=10^6$)!\n",
"\n",
"## Computers are very picky about grammar rules and typos\n",
"\n",
"Look at"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" print 5*0.6 - 0.5*9.81*0.6**2\n",
" write 5*0,6 - 0,5*9,81*0,6^2\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Would you consider these two lines to be equal?\n",
"\n",
" * Humans may say *yes*, computers always *no*\n",
"\n",
" * The second line has no meaning as a Python program\n",
"\n",
" * `write` is not a legal Python word in this context, comma has another\n",
" meaning than in math, and the hat is not exponentiation\n",
"\n",
" * We have to be extremely accurate with how we write computer programs!\n",
"\n",
" * It takes time and experience to learn this\n",
"\n",
"\n",
"\n",
"## Programming opens up a new life\n",
"\n",
"> *People only become computer programmers if they're\n",
"> obsessive about details, crave power over machines, and can bear\n",
"> to be told day after day exactly how\n",
"> stupid they are.* G. J. E. Rawlins\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## Store numbers in variables to make a program more readable\n",
"\n",
"From mathematics you are used to variables, e.g.,"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"v_0=5,\\quad g=9.81,\\quad t=0.6,\\quad y = v_0t -\\frac{1}{2}gt^2\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can use variables in a program too, and this makes the last program\n",
"easier to read and understand:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"v0 = 5\n",
"g = 9.81\n",
"t = 0.6\n",
"y = v0*t - 0.5*g*t**2\n",
"print y"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This program spans several lines of text and use variables, otherwise the program performs the same calculations and gives the same output as the previous program\n",
"\n",
"\n",
"\n",
"## There is great flexibility in choosing variable names\n",
"\n",
" * In mathematics we usually use one letter for a variable\n",
"\n",
" * The name of a variable in a program can contain the letters a-z, A-Z, underscore `_` and the digits 0-9, but cannot start with a digit\n",
"\n",
" * Variable names are case-sensitive (e.g., `a` is different from `A`)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"initial_velocity = 5\n",
"accel_of_gravity = 9.81\n",
"TIME = 0.6\n",
"VerticalPositionOfBall = initial_velocity*TIME - \\\n",
" 0.5*accel_of_gravity*TIME**2\n",
"print VerticalPositionOfBall"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"(Note: the backslash allows an instruction to be continued on the next line)\n",
"\n",
"\n",
"\n",
"Good variable names make a program easier to understand!\n",
"\n",
"\n",
"\n",
"## Some words are reserved in Python\n",
"\n",
"Certain words have a special meaning in Python and cannot be used as variable names. These are: `and`,\n",
"`as`,\n",
"`assert`,\n",
"`break`,\n",
"`class`,\n",
"`continue`,\n",
"`def`,\n",
"`del`,\n",
"`elif`,\n",
"`else`,\n",
"`except`,\n",
"`exec`,\n",
"`finally`,\n",
"`for`,\n",
"`from`,\n",
"`global`,\n",
"`if`,\n",
"`import`,\n",
"`in`,\n",
"`is`,\n",
"`lambda`,\n",
"`not`,\n",
"`or`,\n",
"`pass`,\n",
"`print`,\n",
"`raise`,\n",
"`return`,\n",
"`try`,\n",
"`with`,\n",
"`while`, and\n",
"`yield`.\n",
"\n",
"\n",
"\n",
"## Comments are useful to explain how you think in programs\n",
"\n",
"**Program with comments:**"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# program for computing the height of a ball\n",
"# in vertical motion\n",
"v0 = 5 # initial velocity\n",
"g = 9.81 # acceleration of gravity\n",
"t = 0.6 # time\n",
"y = v0*t - 0.5*g*t**2 # vertical position\n",
"print y"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Note:**\n",
"\n",
" * Everything after `#` on a line is a comment and ignored by Python\n",
"\n",
" * Comments are used to explain what the computer instructions mean, what variables mean, how the programmer reasoned when she wrote the program, etc.\n",
"\n",
" * Bad comments say no more than the code: `a = 5 # set a to 5`\n",
"\n",
"\n",
"\n",
"## Comments are not always ignored....\n",
"\n",
"Normal rule: Python programs, including comments, can only contain characters from the English alphabet.\n",
"\n",
"IPython notebook allows non-English characters (but ordinary Python does\n",
"not unless you have a line `# -*- coding: utf-8 -*-` in the code)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" hilsen = 'Kjære Åsmund!' # er æ og Å lov i en streng?\n",
" print hilsen\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The printf syntax gives great flexibility in formatting text with numbers\n",
"\n",
"Output from calculations often contain text and numbers, e.g.,"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" At t=0.6 s, y is 1.23 m.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We want to control the formatting of numbers: no of decimals, style: `0.6` vs `6E-01` or `6.0e-01`. So-called *printf formatting* is useful for this purpose:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"t = 0.6; y = 1.2342\n",
"print 'At t=%g s, y is %.2f m.' % (t, y)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The printf format has \"slots\" where the variables listed at the end are put: `%g` $\\leftarrow$ `t`, `%.2f` $\\leftarrow$ `y`\n",
"\n",
"\n",
"\n",
"## Examples on different printf formats"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" %g most compact formatting of a real number\n",
" %f decimal notation (-34.674)\n",
" %10.3f decimal notation, 3 decimals, field width 10\n",
" %.3f decimal notation, 3 decimals, minimum width\n",
" %e or %E scientific notation (1.42e-02 or 1.42E-02)\n",
" %9.2e scientific notation, 2 decimals, field width 9\n",
" %d integer\n",
" %5d integer in a field of width 5 characters\n",
" %s string (text)\n",
" %-20s string, field width 20, left-adjusted\n",
" %% the percentage sign % itself\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"(See the the book for more explanation and overview)\n",
"\n",
"\n",
"\n",
"## Using printf formatting in our program\n",
"\n",
"Triple-quoted strings (`\"\"\"`) can be used for multi-line output, and here we combine such a string with printf formatting:"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"v0 = 5\n",
"g = 9.81\n",
"t = 0.6\n",
"y = v0*t - 0.5*g*t**2\n",
"\n",
"print \"\"\"\n",
"At t=%f s, a ball with\n",
"initial velocity v0=%.3E m/s\n",
"is located at the height %.2f m.\n",
"\"\"\" % (t, v0, y)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Some frequently used computer science terms\n",
"\n",
" * Program or code or application\n",
"\n",
" * Source code (program text)\n",
"\n",
" * Code/program snippet\n",
"\n",
" * Execute or run a program\n",
"\n",
" * Algorithm (recipe for a program)\n",
"\n",
" * Implementation (writing the program)\n",
"\n",
" * Verification (does the program work correctly?)\n",
"\n",
" * Bugs (errors) and debugging\n",
"\n",
"\n",
"\n",
"Computer science meaning of terms is often different from the human language meaning\n",
"\n",
"\n",
"\n",
"## A program consists of statements"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = 1 # 1st statement (assignment statement)\n",
"b = 2 # 2nd statement (assignment statement)\n",
"c = a + b # 3rd statement (assignment statement)\n",
"print c # 4th statement (print statement)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Normal rule: one statement per line, but\n",
"multiple statements per line is possible with a semicolon\n",
"in between the statements:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = 1; b = 2; c = a + b; print c"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Assignment statements evaluate right-hand side and assign the result to the variable on the left-hand side"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"myvar = 10\n",
"myvar = 3*myvar # = 30\n",
"myvar"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Syntax is the exact specification of instructions to the computer\n",
"\n",
"Programs must have correct syntax, i.e., correct use of the computer language grammar rules, and no misprints!\n",
"\n",
"\n",
"\n",
"**This is a program with two syntax errors:**"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"myvar = 5.2\n",
"prinnt Myvar"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Only the first encountered error is reported and the program is stopped (correct the error and continue with next error)\n",
"\n",
"\n",
"\n",
"> *Programming demands significantly higher standard of accuracy. Things don't simply have to make sense to another human being, they must make sense to a computer.* Donald Knuth, computer scientist, 1938-\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## Blanks (whitespace) can be used to nicely format the program text\n",
"\n",
"Blanks may or may not be important in Python programs.\n",
"These statements are equivalent (blanks do not matter):"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"v0=3\n",
"v0 = 3\n",
"v0= 3\n",
"v0 = 3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here blanks do matter:"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"counter = 1\n",
"while counter <= 4:\n",
" counter = counter + 1 # correct (4 leading blanks)\n",
"\n",
"while counter <= 4:\n",
"counter = counter + 1 # invalid syntax"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"(more about this in Ch. 2)\n",
"\n",
"\n",
"\n",
"## A program takes some known *input* data and computes some *output* data"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"v0 = 3; g = 9.81; t = 0.6\n",
"position = v0*t - 0.5*g*t*t\n",
"velocity = v0 - g*t\n",
"print 'position:', position, 'velocity:', velocity"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here:\n",
"\n",
" * Input: `v0`, `g`, and `t`\n",
"\n",
" * Output: `position` and `velocity`\n",
"\n",
"\n",
"\n",
"## An operating system (OS) is a set of programs managing hardware and software resources on a computer\n",
"\n",
" * Linux, Unix (Ubuntu, RedHat, Suse, Solaris)\n",
"\n",
" * Windows (95, 98, NT, ME, 2000, XP, Vista, 7, 8)\n",
"\n",
" * Macintosh (old Mac OS, Mac OS X)\n",
"\n",
" * Mac OS X $\\approx$ Unix $\\approx$ Linux $\\neq$ Windows\n",
"\n",
" * Typical OS commands are quite similar:\n",
"\n",
" * Linux/Unix: `mkdir folder; cd folder; ls`\n",
"\n",
" * Windows: `mkdir folder; cd folder; dir`\n",
"\n",
"\n",
" * Python supports cross-platform programming, i.e., a program is independent of which OS we run the program on\n",
"\n",
"\n",
"\n",
"## Evaluating a formula for temperature conversion\n",
"\n",
"Given $C$ as a temperature in Celsius degrees,\n",
"compute the corresponding Fahrenheit degrees $F$:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"F = \\frac{9}{5}C + 32\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Program:"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"C = 21\n",
"F = (9/5)*C + 32\n",
"print F"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## We must always check that a new program calculates the right answer\n",
"\n",
"**Using a calculator:**\n",
"\n",
"9/5 times 21 plus 32 is 69.8, not 53.\n",
"\n",
"\n",
"\n",
"## The error is caused by (unintended) integer division\n",
"\n",
" * 9/5 is not 1.8 but 1 in most computer languages (!)\n",
"\n",
" * If $a$ and $b$ are integers, $a/b$ implies integer division: the largest integer $c$ such that $cb\\leq a$\n",
"\n",
" * Examples: $1/5=0$, $2/5=0$, $7/5=1$, $12/5=2$\n",
"\n",
" * In mathematics, 9/5 is a real number (1.8) - this is called float division in Python and is the division we want\n",
"\n",
" * One of the operands ($a$ or $b$) in $a/b$ must be a real number (\"float\") to get float division\n",
"\n",
" * A float in Python has a dot (or decimals): `9.0` or `9.` is float\n",
"\n",
" * No dot implies integer: `9` is an integer\n",
"\n",
" * `9.0/5` yields `1.8`, `9/5.` yields `1.8`, `9/5` yields `1`\n",
"\n",
"Corrected program (with correct output 69.8):"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"C = 21\n",
"F = (9.0/5)*C + 32\n",
"print F"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Everything in Python is an object\n",
"\n",
"Variables refer to objects:"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = 5 # a refers to an integer (int) object\n",
"b = 9 # b refers to an integer (int) object\n",
"c = 9.0 # c refers to a real number (float) object\n",
"d = b/a # d refers to an int/int => int object\n",
"e = c/a # e refers to float/int => float object\n",
"s = 'b/a=%g' % (b/a) # s is a string/text (str) object\n",
"print d, e, s"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can convert between object types:"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = 3 # a is int\n",
"b = float(a) # b is float 3.0\n",
"c = 3.9 # c is float\n",
"d = int(c) # d is int 3\n",
"d = round(c) # d is float 4.0\n",
"d = int(round(c)) # d is int 4\n",
"d = str(c) # d is str '3.9'\n",
"e = '-4.2' # e is str\n",
"f = float(e) # f is float -4.2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Arithmetic expressions are evaluated as you have learned in mathematics\n",
"\n",
" * Example: $\\frac{5}{9} + 2a^4/2$, in Python written as `5/9 + 2*a**4/2`\n",
"\n",
" * Same rules as in mathematics: proceed term by term (additions/subtractions) from the left, compute powers first, then multiplication and division, in each term\n",
"\n",
" * `r1 = 5/9` (=0)\n",
"\n",
" * `r2 = a**4`\n",
"\n",
" * `r3 = 2*r2`\n",
"\n",
" * `r4 = r3/2`\n",
"\n",
" * `r5 = r1 + r4`\n",
"\n",
" * Use parenthesis to override these default rules - or use parenthesis to explicitly tell how the rules work: \n",
" `(5/9) + (2*(a**4))/2`\n",
"\n",
"\n",
"\n",
"## Standard mathematical functions are found in the `math` module\n",
"\n",
" * What if we need to compute $\\sin x$, $\\cos x$, $\\ln x$, etc. in a program?\n",
"\n",
" * Such functions are available in Python's `math` module\n",
"\n",
" * In general: lots of useful functionality in Python is available in modules - but modules must be *imported* in our programs\n",
"\n",
"Compute $\\sqrt{2}$ using the `sqrt` function in the `math` module:"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import math\n",
"r = math.sqrt(2)\n",
"# or\n",
"from math import sqrt\n",
"r = sqrt(2)\n",
"# or\n",
"from math import * # import everything in math\n",
"r = sqrt(2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Another example on computing with functions from `math`\n",
"\n",
"Evaluate"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"Q = \\sin x\\cos x + 4\\ln x\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"for $x=1.2$."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from math import sin, cos, log\n",
"x = 1.2\n",
"Q = sin(x)*cos(x) + 4*log(x) # log is ln (base e)\n",
"print Q"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Computers have inexact arithmetics because of rounding errors\n",
"\n",
"Let us compute $1/49\\cdot 49$ and $1/51\\cdot 51$:"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"v1 = 1/49.0*49\n",
"v2 = 1/51.0*51\n",
"print '%.16f %.16f' % (v1, v2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note:\n",
"\n",
" * Most real numbers are represented inexactly on a computer (17 digits)\n",
"\n",
" * Neither 1/49 nor 1/51 is represented exactly, the error is typically $10^{-16}$\n",
"\n",
" * Sometimes such small errors propagate to the final answer, sometimes not, and somtimes the small errors accumulate through many mathematical operations\n",
"\n",
" * Lesson learned: real numbers on a computer and the results of mathematical computations are only approximate\n",
"\n",
"\n",
"\n",
"## Test that a calculation is correct\n",
"\n",
"What is printed?"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = 1; b = 2;\n",
"computed = a + b\n",
"expected = 3\n",
"correct = computed == expected\n",
"print 'Correct:', correct"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Change to `a = 0.1` and `b = 0.2` (`expected = 0.3`). What is now printed?\n",
"Why? How can the comparison be performed?\n",
"\n",
"## Answer to exercise on previous slide: use equality test with tolerance!"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = 0.1; b = 0.2; expected = 0.3\n",
"a + b == expected"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print '%.17f\\n%.17f\\n%.17f\\n%.17f' % (0.1, 0.2, 0.1 + 0.2, 0.3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Another example involving math functions\n",
"\n",
"The $\\sinh x$ function is defined as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\sinh (x) = \\frac{1}{2}\\left(e^{x} - e^{-x}\\right)\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can evaluate this function in three ways:\n",
"\n",
" 1. `math.sinh`\n",
"\n",
" 2. combination of two `math.exp`\n",
"\n",
" 3. combination of two powers of `math.e`"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from math import sinh, exp, e, pi\n",
"x = 2*pi\n",
"r1 = sinh(x)\n",
"r2 = 0.5*(exp(x) - exp(-x))\n",
"r3 = 0.5*(e**x - e**(-x))\n",
"print '%.16f %.16f %.16f' % (r1,r2,r3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Output: `r1` is $267.744894041016\\underline{4369}$, `r2` is\n",
"$267.744894041016\\underline{4369}$, `r3` is\n",
"$267.744894041016\\underline{3232}$ (!)\n",
"\n",
"\n",
"\n",
"## Python can be used interactively as a calculator and to test statements\n",
"\n",
" * So far we have performed calculations in Python *programs*\n",
"\n",
" * Python can also be used interactively in what is known as a *shell*\n",
"\n",
" * Type `python`, `ipython`, or `idle` in the terminal window\n",
"\n",
" * A Python shell is entered where you can write statements after `>>>`\n",
" (IPython has a different prompt)\n",
"\n",
"Here in a notebook all cells with code are in fact interactive shells"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"C = 41\n",
"F = (9.0/5)*C + 32\n",
"print F"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"F"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Previous commands can be recalled and edited\n",
"\n",
"\n",
"\n",
"## Python has full support for complex numbers\n",
"\n",
" * $2+3i$ in mathematics is written as `2 + 3j` in Python"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = -2\n",
"b = 0.5\n",
"s = complex(a, b) # make complex from variables\n",
"s"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"s*w # complex*complex"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"s/w # complex/complex"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"s.real"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"s.imag"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"See the book for additional info\n",
"\n",
"\n",
"\n",
"## Python can also do symbolic computing\n",
"\n",
" * Numerical computing: computation with numbers\n",
"\n",
" * Symbolic computing: work with formulas (as in trad. math)"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from sympy import *\n",
"t, v0, g = symbols('t v0 g')\n",
"y = v0*t - Rational(1,2)*g*t**2\n",
"dydt = diff(y, t) # 1st derivative\n",
"dydt"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print 'acceleration:', diff(y, t, t) # 2nd derivative"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"y2 = integrate(dydt, t)\n",
"y2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## SymPy can do a lot of traditional mathematics"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"y = v0*t - Rational(1,2)*g*t**2\n",
"roots = solve(y, t) # solve y=0 wrt t\n",
"roots"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"x, y = symbols('x y')\n",
"f = -sin(x)*sin(y) + cos(x)*cos(y)\n",
"simplify(f)"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"expand(sin(x+y), trig=True) # requires a trigonometric hint"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Summary of Chapter 1 (part 1)\n",
"\n",
" * Programs must be accurate!\n",
"\n",
" * Variables are names for objects\n",
"\n",
" * We have met different object types: `int`, `float`, `str`\n",
"\n",
" * Choose variable names close to the mathematical symbols in\n",
" the problem being solved\n",
"\n",
" * Arithmetic operations in Python: term by term (+/-) from left to right, power before * and / - as in mathematics; use parenthesis when there is any doubt\n",
"\n",
" * Watch out for unintended integer division!\n",
"\n",
"\n",
"\n",
"## Summary of Chapter 1 (part 2)\n",
"\n",
"Mathematical functions like $\\sin x$ and $\\ln x$ must be imported from the `math` module:"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from math import sin, log\n",
"x = 5\n",
"r = sin(3*log(10*x))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Use printf syntax for full control of output of text and numbers!\n",
"\n",
"Important terms: object, variable, algorithm, statement, assignment, implementation, verification, debugging\n",
"\n",
"\n",
"\n",
"## Programming is challenging\n",
"\n",
"> * *You think you know when you can learn,\n",
"> are more sure when you can write,\n",
"> even more when you can teach,\n",
"> but certain when you can program*\n",
"> \n",
"> * *Within a computer, natural language is unnatural*\n",
"> \n",
"> * *To understand a program you must become both the machine and the program*\n",
"> \n",
"> Alan Perlis, computer scientist, 1922-1990.\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## Summarizing example: throwing a ball (problem)\n",
"\n",
"We throw a ball with velocity $v_0$, at an angle $\\theta$ with the horizontal, from the point $(x=0,y=y_0)$. The trajectory of the ball is a parabola (we neglect air resistance):"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"y = x\\tan\\theta - \\frac{1}{2v_0}\\frac{gx^2}{\\cos^2\\theta} + y_0\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Program tasks:\n",
"\n",
" * initialize input data ($v_0$, $g$, $\\theta$, $y_0$)\n",
"\n",
" * import from `math`\n",
"\n",
" * compute $y$\n",
"\n",
"\n",
" * We give $x$, $y$ and $y_0$ in m, $g = 9.81\\hbox {m/s}^2$, $v_0$ in km/h and $\\theta$ in degrees - this requires conversion of $v_0$ to m/s and $\\theta$ to radians\n",
"\n",
"\n",
"\n",
"## Summarizing example: throwing a ball (solution)\n",
"\n",
"Program:"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"g = 9.81 # m/s**2\n",
"v0 = 15 # km/h\n",
"theta = 60 # degrees\n",
"x = 0.5 # m\n",
"y0 = 1 # m\n",
"\n",
"print \"\"\"v0 = %.1f km/h\n",
"theta = %d degrees\n",
"y0 = %.1f m\n",
"x = %.1f m\"\"\" % (v0, theta, y0, x)\n",
"\n",
"# convert v0 to m/s and theta to radians:\n",
"v0 = v0/3.6\n",
"from math import pi, tan, cos\n",
"theta = theta*pi/180\n",
"\n",
"y = x*tan(theta) - 1/(2*v0)*g*x**2/((cos(theta))**2) + y0\n",
"\n",
"print 'y = %.1f m' % y"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 0
}