In [33]:
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate
from time import time
%matplotlib inline
In [3]:
def Runge_Kutta(f, t, x0):
n = len(x0)
N = len(t)
x = np.zeros((n, N))
x[:, 0] = x0
dt = t[1] - t[0]
for i in range(N - 1):
k1 = f(x[:, i])
k2 = f(x[:, i] + dt * k1 / 2)
k3 = f(x[:, i] + dt * k2 / 2)
k4 = f(x[:, i] + dt * k3)
x[:, i + 1] = x[:, i] + dt * (k1 + 2 * (k2 + k3) + k4) / 6
return x
In [18]:
def Lorenz(X, t=0):
return np.array([10 * (X[1] - X[0]),
28 * X[0] - X[1] - X[0] * X[2],
X[0] * X[1] - 8 * X[2] / 3])
In [19]:
N = 10 ** 4
t = np.linspace(0, 50, N)
x0 = np.array([1, 0, 0])
x = Runge_Kutta(Lorenz, t, x0)
plt.plot(t, x.T)
plt.xlabel('t')
plt.ylabel('x, y, z')
Out[19]:
In [20]:
def Lorenz100(X, t=0):
return np.hstack((10 * (X[100:200] - X[:100]),
28 * X[:100] - X[100:200] - X[:100] * X[200:300],
X[:100] * X[100:200] - 8 * X[200:300] / 3))
In [38]:
N = 10 ** 5
t = np.linspace(0, 50, N)
x0 = np.hstack((np.random.normal(1, .05, size=100), np.zeros(200)))
current_time = time()
x = Runge_Kutta(Lorenz100, t, x0)
print('It took', time() - current_time, 's')
In [43]:
x1 = np.mean(x[:100, :], axis=0)
x2 = np.mean(x[100:200, :], axis=0)
x3 = np.mean(x[200:300, :], axis=0)
In [44]:
plt.plot(t, x1)
plt.plot(t, x2)
plt.plot(t, x3)
plt.xlabel('t')
plt.ylabel('mean of x, mean of y, mean of z')
Out[44]:
In [45]:
var_x1 = np.var(x[:100, :], axis=0)
var_x2 = np.var(x[100:200, :], axis=0)
var_x3 = np.var(x[200:300, :], axis=0)
plt.plot(t, var_x1)
plt.plot(t, var_x2)
plt.plot(t, var_x3)
plt.ylabel('var of x, var of y, var of z')
Out[45]:
In [30]:
def trya():
def Lorenz(x, y, z):
return np.array([10 * (y - x),
28 * x - y - x * z,
x * y - 8 * z / 3])
N = 10 ** 5
t = np.linspace(0, 50, N)
x0 = np.array([1, 0, 0])
n = len(x0)
N = len(t)
x = np.zeros(N)
y = np.zeros(N)
z = np.zeros(N)
#x = x0
dt = t[1] - t[0]
x[0] = 1
for i in range(N - 1):
k1 = Lorenz(x[i], y[i], z[i])
k2 = Lorenz(x[i] + dt * k1[0] / 2, y[i] + dt * k1[1] / 2, z[i] + dt * k1[2] / 2)
k3 = Lorenz(x[i] + dt * k2[0] / 2, y[i] + dt * k2[1] / 2, z[i] + dt * k2[2] / 2)
k4 = Lorenz(x[i] + dt * k3[0], y[i] + dt * k3[1], z[i] + dt * k3[2])
x[i + 1] = x[i] + dt * (k1[0] + 2 * (k2[0] + k3[0]) + k4[0]) / 6
y[i + 1] = y[i] + dt * (k1[1] + 2 * (k2[1] + k3[1]) + k4[1]) / 6
z[i + 1] = z[i] + dt * (k1[2] + 2 * (k2[2] + k3[2]) + k4[2]) / 6
%timeit trya()
In [30]:
np.random.randn(100)
Out[30]:
In [31]:
10 ** 5
Out[31]:
In [ ]: