@bintou
2017-11-01T14:46:31.000000Z
字数 1756
阅读 2272
未分类
def rand_walk(n):step = 0for i in range(1, n):#temp = randint(0,2)temp = ZZ.random_element(0,3)if temp == 2:step += 1elif temp == 1:step -= 1# Output the result.print "Derivation from orgin", stepprint "The expectation from the orgin is:", floor(sqrt(n))#Define a rand_walk using RHdef rand_walk_rh(n):step = 0for i in range(1, n + 1):fac = factor(i)length = len(fac)stay = falsefor j in range(length):if fac[j][1] > 1:print i, "don't move"stay = Truebreakif not stay:if is_odd(length):step += 1print i, "move right"else:step -=1print i, "move left"# Output the result.print "Derivation from orgin", stepprint "The expectation from the orgin is:", floor(sqrt(n))
#https://www.quora.com/How-do-I-solve-the-drunkards-walk-or-random-walk-simulation-using-Python-languageimport randomdef RandomWalk1(n):# n-length random walk on the number linereturn [1 if random.random() > 0.5 else -1 for i in xrange(n)]def RandomWalk2(n):# n-length random walk on the number linereturn [random.choice([-1, 1]) for i in xrange(n)]def RandomWalkFinalPosition(n):return sum(RandomWalk1(n))import numpy as npdef RandomWalkNP(n):return np.random.choice([-1, 1], n)def RandomWalkGenerator1():while True:yield 1 if random.random() > 0.5 else -1def RandomWalkGenerator2(n=float('inf')):step = 0while step < n:step += 1yield 1 if random.random() > 0.5 else -1import randomdef Step(n_dim):move = [0 for i in xrange(n_dim)]dimension_to_move = random.randint(0, n_dim-1)direction = 1 if random.random() > 0.5 else -1move[dimension_to_move] = directionreturn movedef RandomWalkMulti(n_steps, n_dim):return [Step(n_dim) for i in xrange(n_steps)]#https://plot.ly/python/random-walk/#http://mooc.ee/MTAT.03.236/2014_fall/uploads/Main/drunkard1.pdf#https://stackoverflow.com/questions/9421928/another-simple-random-walk-simulation-using-pythontwo-dimensional#https://stackoverflow.com/questions/26195815/python-drunkards-walk
