In [47]:
# Importing some python libraries and stuff. 

import matplotlib.pyplot as pl
import numpy as np
from numpy.random import randn
import seaborn as sns
%matplotlib inline

# Fixing figure sizes
from pylab import rcParams
rcParams['figure.figsize'] = 10,7

Discrete approximation to Brownian motion


In [1]:
# Setting up some parameters. 

T = 1; # Final time
n = 500; # Number of points to use in discretization
Dt = float(T)/n;
print 'Stepsize =', Dt,'.'


Stepsize = 0.002 .

In [80]:
def pathGenerate(npath,n, Dt=0.002):
    # Function that generates discrete approximations to a brownian path.
    Wiener = np.zeros([n,npath])

    for j in xrange(npath):
        for i in xrange(n-1):
            Wiener[i+1,j] = Wiener[i,j]+np.sqrt(Dt)*randn()
    
    return Wiener

t = np.linspace(0,T,n)

In [69]:
Wiener = pathGenerate(10, n)
WienerMean = np.mean(Wiener,axis=1)
WienerVar  = np.var(Wiener,axis=1)
pl.errorbar(t, WienerMean,yerr=np.sqrt(WienerVar),
            color=sns.xkcd_rgb['pale red'],ecolor=sns.xkcd_rgb['denim blue'],linewidth=5)
pl.legend(['Mean of paths', 'Uncertainty (standard deviation)'],loc=0)


Out[69]:
<matplotlib.legend.Legend at 0x7f358f131810>

First case is with ten paths. We can see that the mean path hasn't quite converged yet.


In [70]:
Wiener = pathGenerate(100, n)
WienerMean = np.mean(Wiener,axis=1)
WienerVar  = np.var(Wiener,axis=1)
pl.errorbar(t, WienerMean,yerr=np.sqrt(WienerVar),
            color=sns.xkcd_rgb['pale red'],ecolor=sns.xkcd_rgb['denim blue'],linewidth=5)
pl.legend(['Mean of paths', 'Uncertainty (standard deviation)'],loc=0)


Out[70]:
<matplotlib.legend.Legend at 0x7f358ef5e7d0>

The picture looks much better with a hundred paths.


In [81]:
Wiener = pathGenerate(1000, n)
WienerMean = np.mean(Wiener,axis=1)
WienerVar  = np.var(Wiener,axis=1)
pl.errorbar(t, WienerMean,yerr=np.sqrt(WienerVar),
            color=sns.xkcd_rgb['pale red'],ecolor=sns.xkcd_rgb['denim blue'],linewidth=5)
pl.legend(['Mean of paths', 'Uncertainty (standard deviation)'],loc=0)
pl.title('Using a thousand simulated paths.',fontsize=15)


Out[81]:
<matplotlib.text.Text at 0x7f358ea65610>

And with a thousand paths, we can clearly see the convergence of the mean. Also, the confidence region shows the correct growth.


In [78]:
n=10
t = np.linspace(0,T,n)
Wiener = pathGenerate(10, n)
WienerMean = np.mean(Wiener,axis=1)
WienerVar  = np.var(Wiener,axis=1)
pl.errorbar(range(0,n), WienerMean,yerr=np.sqrt(WienerVar),
            color=sns.xkcd_rgb['pale red'],ecolor=sns.xkcd_rgb['denim blue'],linewidth=5)
pl.legend(['Mean of paths', 'Uncertainty (standard deviation)'],loc=0)
pl.title('For comparison, here is another plot with only 10 points', fontsize=15)


Out[78]:
<matplotlib.text.Text at 0x7f358eafc190>