This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
sigma = 1. # Standard deviation.
mu = 10. # Mean.
tau = .05 # Time constant.
dt = .001 # Time step.
T = 1. # Total time.
n = int(T/dt) # Number of time steps.
t = np.linspace(0., T, n) # Vector of times.
sigma_bis = sigma * np.sqrt(2. / tau)
sqrtdt = np.sqrt(dt)
x = np.zeros(n)
for i in range(n-1):
x[i+1] = x[i] + dt*(-(x[i]-mu)/tau) + \
sigma_bis * sqrtdt * np.random.randn()
plt.figure(figsize=(6,3));
plt.plot(t, x);
X
that will contain all realizations of the process at a given time (i.e. we do not keep the memory of all realizations at all times). This vector will be completely updated at every time step. We will show the estimated distribution (histograms) at several points in time.ntrials = 10000
X = np.zeros(ntrials)
# We create bins for the histograms.
bins = np.linspace(-2., 14., 100);
plt.figure(figsize=(6,3));
for i in range(n):
# We update the process independently for all trials.
X += dt*(-(X-mu)/tau) + \
sigma_bis*sqrtdt*np.random.randn(ntrials)
# We display the histogram for a few points in time.
if i in (5, 50, 900):
hist, _ = np.histogram(X, bins=bins)
plt.plot((bins[1:]+bins[:-1])/2, hist,
{5: '-', 50: '.', 900: '-.',}[i],
label="t={0:.2f}".format(i*dt));
plt.legend();
The distribution of the process tends to a Gaussian distribution with mean $\mu=10$ and standard deviation $\sigma=1$. The process would be stationary if the initial distribution was also a Gaussian with the adequate parameters.
You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).
IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).