| Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license. (c) Kyle T. Mandli |
|
The easiest way to install all the components you will need for the class is to use Continuum Analytics' Anaconda distribution. We will be using python 2.7.x for all in class demos and homework so I strongly suggest you do not get the Python 3.4 version.
Alternatives to using Anaconda also exist in the form of Enthought's Canopy distribution which provides all the tools you will need as well along with an IDE (development environment).
Instead of running things locally on your machine there are a number of cloud services that you are welcome to use in order to get everything running easily.
Python is a dynamic, interpreted language used throughout computational engineering and science. Due to its ease of use, cost, and available tools we will be learning the material in this course using Python tools exclusively. For those who are coming in without prior Python knowledge but a strong programming background this lecture should acquaint you with the basics. For people who do not know Python and do not have a strong programming background it is strongly recommended that you take the time to look through the other tutorials mentioned above.
In [1]:
1 / 2
Python returns the floor of the 1 / 2 because we gave it integers to divide. It then interprets the result as also needing to be an integer. If one of the numbers was a decimal number we would have a decimal number as a result (really these are floating point numbers float).
In [2]:
1. / 2
In compound statements it can become more difficult to figure out where possible rounding might occur so be careful when you evaluate statements.
In [3]:
4. + 4.0**(3.0/2)
Python also understands imaginary numbers:
In [4]:
4 + 3j
Some of the more advanced mathematical functions are stored in modules. In order to use these functions we must first import them into our notebook and then use them.
In [5]:
import math
In [6]:
math?
In [7]:
math.sqrt(2.0)
In [8]:
math.sin(math.pi / 2.0)
In [9]:
from math import *
sin(pi)
In [10]:
num_students = 80
room_capacity = 85
(room_capacity - num_students) / room_capacity * 100.0
Note that we do not get what we expect from this expression as we expected from above. What would we have to change to get this to work?
We could go back to change our initializations but we could also use the function float to force these values to be of float type:
In [11]:
float(room_capacity - num_students) / float(room_capacity) * 100.0
In [12]:
x = 4
if x > 5:
print "x is greater than 5"
elif x < 5:
print "x is less than 5"
else:
print "x is equal to 5"
for allows us to repeat tasks over a range of values or objects.
In [13]:
for i in range(5):
print i
In [14]:
for i in range(3,7):
print i
In [15]:
for animal in ['cat', 'dog', 'chinchilla']:
print animal
In [16]:
for n in range(2, 10):
is_prime = True
for x in range(2, n):
if n % x == 0:
print n, 'equals', x, '*', n / x
is_prime = False
break
if is_prime:
print "%s is a prime number" % (n)
In [17]:
def my_print_function(x):
print x
my_print_function(3)
In [18]:
def my_add_function(a, b):
return a + b, b
my_add_function(3.0, 5.0)
In [19]:
def my_crazy_function(a, b, c=1.0):
d = a + b**c
return d
my_crazy_function(2.0, 3.0), my_crazy_function(2.0, 3.0, 2.0), my_crazy_function(2.0, 3.0, c=2.0)
In [20]:
def my_other_function(a, b, c=1.0):
return a + b, a + b**c, a + b**(3.0 / 7.0)
my_other_function(2.0, 3.0, c=2.0)
In [21]:
def fibonacci(n):
"""Return a list of the Fibonacci sequence up to n"""
values = [0, 1]
while values[-1] <= n:
values.append(values[-1] + values[-2])
print values
return values
fibonacci(100)
fibonacci?
The most important part of NumPy is the specification of an array object called an ndarray. This object as its name suggests stores array like information in multiple dimensions. These objects allow a programmer to access the data in a multitude of different ways as well as create common types of arrays and operate on these arrays easily.
In [22]:
import numpy
In [23]:
my_array = numpy.array([[1, 2], [3, 4]])
print my_array
In [24]:
numpy.linspace(-1, 1, 10)
In [25]:
numpy.zeros([3, 3])
In [26]:
numpy.ones([2, 3, 2])
In [27]:
numpy.empty([2,3])
In [28]:
my_array[0, 1]
In [29]:
my_array[:,0]
In [30]:
my_vec = numpy.array([[1], [2]])
print my_vec
In [31]:
numpy.dot(my_array, my_vec)
numpy.cross?
In [32]:
my_array * my_vec
In [33]:
A = numpy.array([[1, 2, 3], [4, 5, 6]])
print "A Shape = ", A.shape
print A
In [34]:
B = A.reshape((6,1))
print "A Shape = ", A.shape
print "B Shape = ", B.shape
print B
In [35]:
numpy.tile(A, (2,2))
In [36]:
A.transpose()
In [37]:
A = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
print A
print A.shape
In [38]:
B = numpy.arange(1,10)
print B
print B.reshape((3,3))
B.reshape?
C = B.reshape((3,3))
In [39]:
print A * C
In [40]:
numpy.dot(A, C)
In [41]:
x = numpy.linspace(-2.0 * numpy.pi, 2.0 * numpy.pi, 62)
y = numpy.sin(x)
print y
In [42]:
x = numpy.linspace(-1, 1, 20)
numpy.sqrt(x)
In [43]:
x = numpy.linspace(-1, 1, 20, dtype=complex)
numpy.sqrt(x)
In [44]:
numpy.linalg.norm(x)
numpy.linalg.norm?
In [45]:
M = numpy.array([[0,2],[8,0]])
b = numpy.array([1,2])
print M
print b
In [46]:
x = numpy.linalg.solve(M,b)
print x
In [47]:
lamda,V = numpy.linalg.eig(M)
print lamda
print V
NumPy contains the basic building blocks for numerical computing where as the SciPy packages contain all the higher-level functionality. Refer to the SciPy webpage for more information on what it contains. There are also a number of SciKits which provide additional functionality
The most common facility for plotting with the Python numerical suite is to use the matplotlib package. We will cover a few of the basic approaches to plotting figures. If you are interested in learning more about matplotlib or are looking to see how you might create a particular plot check out the matplotlib gallery for inspiration.
Refer to the APAM 4300 Notes on matplotlib for detailed examples.
All class notes and assignments will be done within Jupyter notebooks (formally IPython notebooks). It is important that you become acquainted with these as there are a couple of pitfalls that you should be aware of.
Very important in practice to write readable and understandable code. Here are a few things to keep in mind while programming in and out of this class, we will work on this actively as the semester progresses as well. The standard for which Python program are written to is called PEP 8 and contains the following basic guidelines:
docstrings (function descriptions)a = f(1, 2) + g(3, 4)CamelCase for classeslower_case_with_underscores for functions and variablesGood coding style will mean that we can more easily grade your assignments and understand what you are doing. Please make sure to keep this in mind especially when naming variables, making comments, or documenting your functions.