# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 2
#     language: python
#     name: python2
# ---

# +
# 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

# +
# Setting up some parameters. 

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


# +
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)
# -

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)

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

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)

# The picture looks much better with a hundred paths.

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)

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

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)

StarcoderdataJupyterScriptsDedupFiltered