import sys
print sys.path
sys
is a built-in module, it is installed by default.
This module can access system files and variables (for example command line arguments).
The sys.path
is a variable containing various directory paths.
You can import only one function from a module of the whole module.
import math
print math.pi
from itertools import permutations
for p in permutations(['A','B','C']):
print p
You can import files in the current directory.
from lab11 import Node, function
print Node("3+4*5")
print function()
numpy
basics¶Numpy is a module for numerical calculations. It can handle vectors, matrices, arrays and perform linear algebraic calculations, random number generation.
If you have Anaconda then it is installed by default.
You can import a module with an alternative name, just to make it shorter.
import numpy as np
The main object of numpy is ndarray
, short for n-dimensional array, you can create arrays with the
numpy.array
function.
import numpy as np
x = np.arange(1,-1,-0.1)
y = np.array([[1,2,3],[1,2,4]])
print x.dtype
print y.dtype
print x.shape
print y.shape
print x.ndim
print y.ndim
print x
print y
You can perform elementwise operations (+ - * /
) if the arrays are compatible.
a = np.array( [20,30,40,50] )
b = np.arange( 4 )
print a
print b
print
print a+b
print a-b
print b / (b+1.0)
print np.sin(b)
You can add a number to an array which means adding the same number to all of the elements. Same for multiplication and other operations.
b = np.arange(10)
print b
print b ** 2
print b + 10
print b % 3 == 1
The matrix dot product is not the *
operator!
A=np.arange(2,6).reshape(2,2)
B=np.arange(3,-1,-1).reshape(2,2)
print A
print B
print A*B
print A.dot(B)
Note that the reshape
can restructure the elements into a different array.
The number of elements should not change.
The dot
raises an error if the operands are not compatible.
You can use the normal indexing.
x = np.arange(15).reshape(3,5)
print x
print x[0:2]
Or you can take certain columns:
print x[:,3]
print x[2,:3]
You can use a list of indices which slices the corresponding rows (or columns).
a = np.arange(12)**2
i = np.array( [ 1,1,3,8,5 ] )
print a
print a[i]
A = np.arange(15).reshape(3,5)
print
print A
print A[:, [1,0]]
You can call a numpy function with an array parameter which performs (mostly) elementwise operation.
Numpy can calculate mean and standard deviation.
x = np.log(np.arange(2,10,0.5))
print x
print x.sum()
print x.mean()
print x.std()
To make an array filled with zeros or ones you can call zeros
or ones
, similar to MatLab.
The identity matrix is eye
.
print np.zeros([4,3], dtype=int)
x = np.ones([4,1])
print x.dtype
print np.eye(4)
You can generate random numbers or array of numbers.
np.random.rand(3,4)
You can generate uniform numbers drawn from $[-2, 2]$ in two ways:
print np.random.rand(10)*4-2
print np.random.uniform(size=(10, 2), high=2, low=-2)
The matplotlib
module can plot functions.
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
A simple plot first. If you don't specify the $x$ values, the range $[0, 1, 2 \ldots]$ is used instead.
plt.plot([1,2,4])
plt.ylabel('some numbers')
plt.show()
These libraries cannot calculate symbolically, like Sage, just makes a series of lines between the plotted points.
Let's plot a sine curve.
plt.plot(np.arange(0,2*np.pi,0.05), np.sin(np.arange(0,2*np.pi,0.05)), 'y')
plt.axis([0,2*np.pi,-1,1])
plt.show()
Monte-Carlo simulation is an easy but not too fast way to estimate an integral.
To calculate $\int_{-2}^2e^{-x^2}\,\mathrm{d}x$ you draw random points in the rectangle $[-2,2]\times[0,1]$ and count how many points fell under the graph: $e^{-x^2} > y$.
The ratio of the points under the curve times the size of the rectangle is an approximation of the area.
X = np.random.rand(500000,2)
X[:,0] = X[:,0]*4-2
J = np.where(X[:,1] < np.exp(-X[:,0]**2))[0]
print len(J) / 500000.0 * 4
In picture:
Xp = X[:2000]
Ip = [i for i in range(len(Xp)) if i in J]
Inp = [i for i in range(len(Xp)) if i not in J]
plt.plot(Xp[Ip,0],Xp[Ip,1], 'bd', Xp[Inp,0],Xp[Inp,1], 'rd')
plt.show()