import numpy as np
import matplotlib.pyplot as plt

# first passage time of random walker
# the average of the first passage time grows
# the more experiments you average (n)
# eventually diverges to infinity
# see https://www.math.ucdavis.edu/~tracy/courses/math135A/UsefullCourseMaterial/firstPassage.pdf last paragraph

p = 0.5
thresh = 1.0
rep = 1
rn = 10000
n = 2
meantimes = np.zeros(rep)
for i in range(rep):
    times = np.zeros(n)
    for k in  range(n):
        xx = 0.0
        xxinx = 0
        while True:
            r = np.random.rand(rn)
            x = np.zeros(len(r))
            x[r < p] = 1.0
            x[r >= p]= -1.0
            y = xx + np.cumsum(x)
            inx = np.where(y > thresh)[0]
            if len(inx) > 0:
                times[k] = xxinx + inx[0]
                break
            xx = y[-1]
            xxinx += len(x)
    meantimes[i] = np.mean(times)
print np.mean(meantimes)