import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
def dP_dt(P, t):
G = 1.0
M = 1.0
x, y, vx, vy = P
r3 = np.hypot(x, y)**3
ax = -G*M*x/r3
ay = -G*M*y/r3
return np.array([vx, vy, ax, ay])
def euler_path(tmax, h, P0):
steps = int(tmax/h)
path = np.empty((steps+1, 4))
P = np.copy(P0)
path[0] = P
for i in range(steps):
P += h*dP_dt(P, i*h)
path[i+1] = P
return path
P0 = np.array([1., 0., 0., 1.])
print(euler_path(1, .1, P0))
def plot_euler(tmax, h, P0):
path = euler_path(tmax, h, P0)
plt.plot(path[:,0], path[:,1])
plt.axis('equal')
plt.plot(0, 0, 'yo', ms=10)
plt.figure(figsize=(8,8))
P0 = np.array([1., 0., 0., 1.])
plot_euler(2, .1, P0)
plt.figure(figsize=(8,8))
P0 = np.array([1., 0., 0., 1.])
plot_euler(10, .1, P0)
plt.figure(figsize=(8,8))
P0 = np.array([1., 0., 0., 1.])
plot_euler(100, .1, P0)
P0 = np.array([1., 0., 0., 1.])
plt.figure(figsize=(15, 5))
for i, h in enumerate([.1, .01, .001]):
plt.subplot(1, 3, i+1)
plot_euler(100, h, P0)
plt.grid()
def calculate_path(tmax, h, P0):
steps = int(tmax/h)
path = np.empty((steps+1, 4))
P = np.copy(P0)
path[0] = P
for i in range(steps):
F1 = h*dP_dt(P, i*h)
F2 = h*dP_dt(P+F1, (i+1)*h)
P += (F1 + F2)/2
path[i+1] = P
return path
def plot_path(tmax, h, P0):
path = calculate_path(tmax, h, P0)
plt.plot(path[:,0], path[:,1])
plt.axis('equal')
plt.plot(0, 0, 'yo', ms=10)
P0 = np.array([1., 0., 0., 1.])
plt.figure(figsize=(15, 5))
for i, h in enumerate([.1, .01, .001]):
plt.subplot(1, 3, i+1)
plot_path(100, h, P0)
plt.grid()
for i, char in enumerate('abc'):
print(i, char)
def distance(x, y):
return np.sqrt(x**2 + y**2)
print(distance(3, 4))
npts = 5
x = np.linspace(-1, 1, npts)
y = np.linspace(-1, 1, npts)
print(x)
print(y)
X, Y = np.meshgrid(x, y)
print(X)
print(Y)
Z = distance(X, Y)
print(Z)
plt.contour(x, y, Z)
npts = 50
x = np.linspace(-1, 1, npts)
y = np.linspace(-1, 1, npts)
X, Y = np.meshgrid(x, y)
Z = distance(X, Y)
plt.contour(x, y, Z)
plt.colorbar()
npts = 50
x = np.linspace(-1, 1, npts)
y = np.linspace(-1, 1, npts)
X, Y = np.meshgrid(x, y)
Z = distance(X, Y)
plt.figure(figsize=(12, 10))
plt.contourf(x, y, Z)
plt.colorbar()
npts = 50
x = np.linspace(-1, 1, npts)
y = np.linspace(-1, 1, npts)
X, Y = np.meshgrid(x, y)
Z = distance(X, Y)
plt.figure(figsize=(12, 10))
plt.contourf(x, y, Z, cmap='Blues')
plt.colorbar()
P0 = np.array([1., 0., 0., 1.])
plt.figure(figsize=(15, 5))
for i, h in enumerate([.1, .01, .001]):
plt.subplot(1, 3, i+1, frameon=False)
plot_path(100, h, P0)
#plt.grid()
t = np.linspace(0, 2*np.pi)
nrows = 8
ncols = 8
nplot = 1
for col in range(ncols):
for row in range(nrows):
plt.subplot(nrows, ncols, nplot, frameon=False)
plt.plot(np.cos(col*t), np.sin(row*t))
plt.xticks([])
plt.yticks([])
nplot += 1