import numpy as np
A key feature of numpy are numpy arrays that resemble lists.
A list can be converted into a numpy array using the np.array()
function:
numbers = [1, 2, 3]
print(numbers)
a = np.array(numbers)
print(a)
We can use the type()
function to verify that a
is a numpy array:
type(numbers)
type(a)
b = 10
type(b)
Many mathematical operations can be performed on all elements of a numpy array at once:
print(a)
print(5*a)
print(5*numbers)
b = list(a)
print(b)
print(a**2)
a += 10
print(a)
b = np.array([100, 200, 300])
print(b)
print(a+b)
print(a*b)
The numpy module contains versions of many math functions (trigonometric, logarithmic, etc.) that can be applied to whole arrays:
from math import pi
x = np.array([pi/8, pi/4, pi/2, pi])
y = np.sin(x)
print(y)
Note: math
module functions do not work with numpy arrays:
from math import sin
sin(x)
for
loops work for numpy arrays:
print(a)
for x in a:
print(2*x)
Indexing and slicing for numpy arrays work as for lists:
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
x[0] = 1000
print(x)
print(x[:4])
Note: For lists slicing produces a new list, for numpy arrays it produces a "view" of the origianal array. Changing a slice of a numpy array will change the original array.
a = [1, 2, 3, 4]
b = a[:2]
b[0] = 1000
print(b)
print(a)
a = np.array([1, 2, 3, 4])
b = a[:2]
print(a)
print(b)
b[0] =1000
print(a)
print(b)
To get an independent copy of a numpy use the copy()
function:
a = np.array([1, 2, 3, 4])
b = a[:2].copy()
b[0] = 1000
print(b)
print(a)
a = np.array([1, 2, 3, 4])
print(a)
a.append(100)
1) Use the np.array()
function to convert a list into an array:
a = np.array([1, 2, 3])
print(a)
2) Use np.zeros(n)
to create an array of n zeros:
b = np.zeros(10)
print(b)
By default this creates a array of floats, but this can ve changed by specifying dtype
:
c = np.zeros(10, dtype = 'int')
print(c)
3) The np.ones(n)
function creates an array of n ones:
d = np.ones(10)
print(d)
from math import pi
x = pi*d
print(x)
4) The np.empty(n)
function creates an array of length n with uninitialized values.
y = np.empty(10, dtype= 'int')
print(y)
5) np.arange()
is similar to range()
but it produces an array:
numbers = np.arange(10)
print(numbers)
evens = np.arange(10, 20, 2)
print(evens)
Note: Arguments of np.arange()
can be floats:
w = np.arange(0.3, 1.0, 0.2)
print(w)
6) np.linspace(a, b, n)
creates an array of n
evenly spaces numbers between a
and b
:
z = np.linspace(0, 1, 5)
print(z)
Note: Array functions in general work much faster than functions applied to every element of a list:
from time import time
from math import sin
st = time()
mylist = [sin(x) for x in range(10**7)]
print(time() - st)
st = time()
myarray = np.sin(np.arange(10**7))
print(time() - st)
matplotlib works directly with numpy arrays:
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 1000)
y = np.sin(x)
plt.plot(x, y)
plt.show()
The matplotlib subplot()
function allows to create a matplot figure consisting of several subplots.
The syntax is: plt.subplot(r, c, n)
where:
plt.figure(figsize =(8, 5))
plt.subplot(2, 2, 1) # plot nr 1 on a grid with 2 rows 2 columns
x = np.linspace(-3, 3, 500)
y = np.sin(x)
plt.plot(x, y, 'r')
plt.title('subplot(2,2,1)')
plt.subplot(2, 2, 2) # plot nr 2 on a grid with 2 rows 2 columns
y = np.cos(x)
plt.plot(x, y, 'b')
plt.title('subplot(2,2,2)')
plt.subplot(2, 2, 3) # plot nr 3 on a grid with 2 rows 2 columns
y = x**2
plt.plot(x, y, 'g')
plt.title('subplot(2,2,3)')
plt.subplot(2, 2, 4) # plot nr 4 on a grid with 2 rows 2 columns
y = x
plt.plot(x, y, 'y')
plt.title('subplot(2,2,4)')
plt.show()
Spacing between subplots can be adjusted:
plt.figure(figsize =(8, 5))
# wspace = width space, hspace = height space
plt.subplots_adjust(wspace = 0.2, hspace = 0.4)
plt.subplot(2, 2, 1) # plot nr 1 on a grid with 2 rows 2 columns
x = np.linspace(-3, 3, 500)
y = np.sin(x)
plt.plot(x, y, 'r')
plt.title('subplot(2,2,1)')
plt.subplot(2, 2, 2) # plot nr 2 on a grid with 2 rows 2 columns
y = np.cos(x)
plt.plot(x, y, 'b')
plt.title('subplot(2,2,2)')
plt.subplot(2, 2, 3) # plot nr 3 on a grid with 2 rows 2 columns
y = x**2
plt.plot(x, y, 'g')
plt.title('subplot(2,2,3)')
plt.subplot(2, 2, 4) # plot nr 4 on a grid with 2 rows 2 columns
y = x
plt.plot(x, y, 'y')
plt.title('subplot(2,2,4)')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3, 3, 1000)
plt.figure(figsize=(10, 3))
plt.subplot(1, 2, 1)
y = np.sin(x)
plt.plot(x, y)
plt.subplot(1, 2, 2)
y = np.cos(x)
plt.plot(x, y, 'r')
plt.show()
ab = [[a, b] for a in range(1, r+1) for b in range(1, r+1)]
print(ab)
plt.figure(figsize = (10, 8))
t = np.linspace(-np.pi, np.pi, 500)
for i in range(r**2):
plt.axis('equal')
plt.subplot(r, r, i+1)
a, b = ab[i]
x = np.sin(a*t)
y = np.cos(b*t)
plt.xticks([])
plt.yticks([])
plt.title('a={}, b={}'.format(a, b))
plt.plot(x, y)
plt.suptitle('Lissajous curves')
plt.show()
plt.plot([1, 2, 3], [1, 2,3])
plt.xticks([1, 1.3, 2, 2.25])
plt.show()
Subplots of different shapes can be combined as long as they don't overlap:
plt.figure(figsize=(8,5))
x = np.linspace(-6, 6, 500)
plt.subplot(2, 2, 1)
plt.plot(x, np.sin(x))
plt.title('subplot (2,2,1)')
plt.subplot(2, 2, 3)
plt.plot(x, x*np.cos(x))
plt.title('subplot (2,2,2)')
plt.subplot(1, 2, 2)
plt.plot(x, np.cos(10*x))
plt.title('subplot (1,2,2)')
plt.show()
The plt.subplot()
function returns an axes object which can be used to specify which subplot is active for plotting:
plt.figure(figsize=(8,5))
x = np.linspace(0,6, 500)
ax1 = plt.subplot(2, 1, 1)
plt.plot(x, np.sin(x))
ax2 = plt.subplot(2, 1, 2)
plt.plot(x, np.cos(x), 'g')
plt.axes(ax1) #activate subplot (2,1,1)
plt.plot(x, np.cos(10*x), 'r--')
plt.show()
We can also use the plt.axes()
function to create an axes object and position it any way we want.
Syntax is: plt.axes([x, y, w, h])
where:
(x, y)
- coords of the lower left corner of the axes objectw
- widthh
- heightplt.figure(figsize=(8, 5))
x = np.linspace(0,6, 500)
ax1 = plt.axes([0.2, 0.1, 0.7, 0.5])
ax2 = plt.axes([0.5, 0.4, 0.5, 0.5])
plt.axes(ax1)
plt.plot(x, np.sin(x))
plt.axes(ax2)
plt.plot(x, np.cos(x), 'r')
plt.show()
The simplest population model:
$$x_n = a\cdot x_{n-1}$$Note: This model depends on $a$ and $x_0$-the initial population.
a = 1.1
x = 10000
list1 = []
for n in range(50):
x = a*x
list1.append(int(x))
print(list1)
a = 0.9
x = 10000
list2 = []
for n in range(100):
x = a*x
list2.append(int(x))
print(list2)
plt.plot(list1, 'ro')
plt.show()
plt.plot(list2, 'go')
plt.savefig('test.png')
plt.show()
The mayfly model:
$$y_n = b(1-y_{n-1})y_{n-1}$$Note: this depends on $y_0$ and the parameter $b$.
Note: We consider only $0\le y_0 \le 1$ and $0 \le b \le 4$.