walkers.py

from matplotlib import pyplot
from numpy import array, sqrt
from time import time
bv = lambda x,n: (x&(1<<n)) >> n

class LFSR32:
    
    def __init__(self):
        self.x = int(time())

    def eval(self):
        x = self.x
        self.x = (((self.x << 1) | (bv(x, 31) ^ bv(x, 21) ^ bv(x, 1) ^ bv(x, 0))) 
            & 0xFFFFFFFF)
        return self.x

rng = LFSR32()
def random():
    return rng.eval()

class RandomWalker:
    
    def __init__(self, n):
        self.path = []
        pos = 0
        for i in xrange(n):
            if random() & 1 == 1:
                pos += 1
            else:
                pos -= 1
            self.path.append(pos)

n_walkers = 10
n_pts = 1000
x = range(n_pts)
walkers = []
for i in xrange(n_walkers):
    walker = RandomWalker(n_pts)
    walkers.append(walker.path)
    pyplot.plot(x, walker.path)

walkers = array(walkers)
means = []
variances = []
for i in xrange(n_pts):
    mean = float(sum(walkers[:,i])) / n_walkers
    variance = ( sum(pow(walkers[:,i] - array([mean] * n_walkers), 2)) ) / n_walkers
    means.append(mean)
    variances.append(variance)

stddevs = sqrt(variances)
pyplot.errorbar(x, means, yerr=stddevs*1.5, ecolor=(0.8,0.8,0.8))

pyplot.show()

            

Back to assignment 3