import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
This is a technique to solve a large problem by breaking it into smaller problems of the same type.
It is used here to find the points which map to zero under Newton's Method for Report 4.
def plot_z_back(w, depth):
plt.plot(w.real, w.imag, 'm.', ms=1)
if depth > 0:
for z in np.roots([2, -3*w, 0, 1.]):
plot_z_back(z, depth-1)
plt.figure(figsize=(8,8))
plt.axis('equal')
plot_z_back(0, 1)
plt.xlim(-1,1)
plt.ylim(-1,1)
The points which are mapped to zero constitute the boundaries of the basins of attraction.
plt.figure(figsize=(8,8))
plt.axis('equal')
plot_z_back(0, 7)
plt.xlim(-1,1)
plt.ylim(-1,1)
def testf(x):
return 2 + 2*np.sin(50*x)
x = np.linspace(0, 1, 400)
sample = np.linspace(0, 1, 9)
plt.plot(x, testf(x))
plt.plot(sample, testf(sample), 'ro');
The sample is correlated with the function, leading to a large error in the estimated mean.
print(np.mean(testf(x)))
print(np.mean(testf(sample)))
a = 2
x = np.linspace(0, 1, 400)
plt.plot(x, a*x % 1, 'b.');
a = 123
x = np.linspace(0, 1, 4000)
plt.figure(figsize=(8,8))
plt.plot(x, a*x % 1, 'b.');
def rng(x, npts):
a = 427419669081
m = 999999999989
u = np.empty(npts)
u[0] = x/m
for i in range(1, npts):
x = (a*x) % m
u[i] = x/m
return u
rng(100, 10)
x = np.linspace(0, 1, 9)
print(x)
plt.hist(x, bins=4);
x = np.linspace(0, 1, 9)
print(x)
plt.hist(x, bins=4, normed=True);
This is the random number generator provided with NumPy.
from numpy.random import rand
rand(10)
rand(100)
rand(2,3)
npts = 1000
x, y = rand(2, npts)*2 - 1
radius = 1
plt.figure(figsize=(8,8))
plt.plot(x, y, 'r.')
circle = plt.Circle((0, 0), radius, fill=False)
plt.gca().add_artist(circle)
plt.xlim(-1,1)
plt.ylim(-1,1);
Summing an entire array.
a = np.arange(12).reshape((3, 4))
print(a)
print(np.sum(a))
Summing down the columns of an array.
sum_cols = np.sum(a, axis=0)
print(a.shape)
print(sum_cols)
print(sum_cols.shape)
Summing across the rows of an array.
sum_rows = np.sum(a, axis=1)
print(a.shape)
print(sum_rows)
print(sum_rows.shape)
points = rand(7) < 0.6
print(points)
print(np.sum(points))
ngames = 10
points = rand(7, ngames) < 0.6
scores = np.sum(points, axis=0)
print(scores)
wins = scores >= 4
print(wins)
print(np.mean(wins))