Introduction to Python and Jupyter Notebooks

Execute the following following cell to make numpy routines available as np.xxx. Numpy is the core tool for numerical computing with arrays in Python, see www.scipy-lectures.org for more details.

A cell is executed by Shift+Enter on the keyboard or by Run in the menu.

In [ ]:
# import numpy routines and make them available as np.xxx
import numpy as np

The following cells give some examples of basic Python commands. You can evaluate them one by one.

a) Basics

In [ ]:
# Example: Variables and arithmetics

x = -6
y = 3*x + 5

# Numerical operations via numpy 
print( np.cos( y*np.pi ) )
print( np.abs(x) )
print( np.power(x,3) )

b) Lists

In [ ]:
# create a list a with real numbers 0, 0.1, 0.2,..., 10
m = 10
a = np.arange(0,m,.1)
print("Liste a = ", a)
print("Size of the list is ", np.size(a))

# create a list b with integers 0, 2, 4, ..., 10
b = np.arange(0,m,2)
print("Liste b = ", b)
print("Size of the list is ", np.size(b))

# create a list c with integers 0, -3, -6, ..., -18
n = -18
c = np.arange(0,n,-3)
print("Liste c = ", c)
print("Size of the list is ", np.size(c))

c) Functions and loops

In [ ]:
# Definition of functions 
# NOTE: the indentation is crucial !!!
def foo(x) : 
    return 1.0/(1+25*np.power(x,2))

# for - loop
# NOTE: Again the insertion is crucial !
for i in np.arange(1,5,0.2):
    print(i, foo(i))

d) Plotting (2D)

In [ ]:
# Two dimensional plots can be created with routines from the library
# matplotlib. The following command makes routines from this library
# available as plt.xxx.

import matplotlib.pyplot as plt

h = 0.01
r = np.arange(0,1,h)
s = foo(r)

# Plotting commands are similar to Matlab, see www.scipy-lectures.org.
# You have to evaluate the cell twice to see the plot.

plt.plot( r, np.cos(r), '-b')  #create first plot
plt.plot( r, s, '*r')          #create second plot
plt.ylabel('fnc values')     #label for axis
plt.show()                   #output of plots

e) Functions with several arguments

In [ ]:
def Rosenbrock(a,b,x,y):
    val = np.power( a - x, 2) + b * np.power(y - np.power(x,2), 2 );
    return val

a = 1
b = 2
m = 10
t = np.arange(0,1,1/m)
z = np.zeros(m); # initialise vector of size m with zeroes
for i in np.arange(0,m):
    z[i] = Rosenbrock( a, b, 0, t[i])
print(z)

# the same can be done without a loop:

print(Rosenbrock(a,b,0,t))    

f) Interactive plots

In [ ]:
import matplotlib.pyplot as plt
from ipywidgets import interactive

def pltsin(f) :
    m = 100;
    t = np.arange(0,np.pi,np.pi/m);
    plt.plot(t, np.sin(2*t*f) )
    plt.show()

interactive( pltsin, f = (1,10, 0.1) )

g) Arrays of random numbers

In [ ]:
# Set a seed for the random number generator (You can drop this step
# if you are not interested in reproducable random numbers. Try evaluating
# the cell several times both with and without a seed):
np.random.seed(17)

# create a 2x6 array of standard normally distributed random numbers
noise = np.random.randn(2,6) 
print(noise)
# print the first row (the rows are indexed 0 and 1)
print(noise[0])
# print the second up to the fifth column in the first row
print(noise[0,1:4])

h) Samples from a two dimensional standard normal distribution

In [ ]:
# create 10000 samples with two components each
noise = np.random.randn(2,10000)

# create a scatter plot of the samples. 
plt.scatter(noise[0],noise[1],s=.1)  # parameter s=.1 sets thin points 
plt.show()

i) Samples from a simple random walk

In [ ]:
steps = 1000    #number of steps
k = 8       #number of samples
u = np.random.rand(steps,k)   #create an array of uniform random numbers
noise = np.sign(u-.5)  #transform to an array of random numbers in {-1,+1}

rw = np.cumsum(noise,axis=0)
# For each entry in the second component (axis=1), the matrix rw 
# contains the cumulative sums of the random numbers in the first 
# component (axis=0). Thus the array rw contains simulations of k 
# simple random walks. (Note however that the initial value 0 is not
# contained in the cumulative sum!) We now plot the samples. 

n = np.arange(1,steps+1)
# creates vector with indices n=1,2,3,...,steps

plt.figure(figsize=(9,5), dpi=80)
# sets size of plot; can be dropped
plt.plot(n,rw,linewidth=1.)
# produces a plot of the Brandom walks in the components of bm versus t
plt.show()
# output of plot 

Alternatively, we can explicity compute the cumulative sums in a for-loop:

In [ ]:
rw2 = np.zeros((steps+1,k))
# creates an array filled with zeros indexed between (0,0) and (steps,k-1)

for i in range(steps-1):
    rw2[i+1] = rw2[i]+noise[i]
# computes random walk as cumulative sum (now it starts at 0)

n = np.arange(0,steps+1)
# creates vector with indices n=0,1,2,3,...,steps
    
plt.figure(figsize=(9,5), dpi=80)
plt.plot(n,rw2,linewidth=0.5)
plt.show()

j) Samples from a two dimensional simple random walk

In [ ]:
noise1 = np.random.randn(steps,k)
rw1 = np.cumsum(noise1,axis=0)
noise2 = np.random.randn(steps,k)
rw2 = np.cumsum(noise2,axis=0)

plt.figure(figsize=(8,8), dpi=80)
plt.plot(rw1,rw2,linewidth=.4)
plt.show()
In [ ]: