To simulate the random walk.

  To simulate the random walk.



Python Code for 1D Random Walk : 

# ---------------------------------------------------------------------
# exp -8: To simulate the random walk (1 -d)
# ---------------------------------------------------------------------
import random
import numpy as np
import matplotlib . pyplot as plt
n = 100000 # defining the number of steps
x = np . zeros (n ) # creating empty array
t = np . zeros (n )

# -------- filling the coordinates with random variables --------------
x [0] = random . randint (1 , 10)
for i in range (1 , n):
  t[i ] = i
  val = random . randint (1 , 10)
  if( val >5) :
    x[i ] = x[i -1] + 1
  else :
    x[i ] = x[i -1] - 1

# ---------------- plotting stuff --- ----- ---- ----- ----- ---- ----- ----- ---

fig , ax = plt . subplots ()
plt . title (" Random Walk for 1-D ($n = " + str(n ) + "$ steps )")
fig.set_figwidth(16)
fig.set_figheight(10)
ax . plot (t , x , '-k', ) # rand
ax . plot (t [0] , x [0] , 'go')
ax . plot (t[n -1] , x[n -1] ,'ro')
plt . xlabel (" Number of steps n")
plt . show ()
# ---------------------------------------------------------------------




Python Code (For 2D Random Walk):


# ---------------------------------------------------------------------
# exp -8: To simulate the random walk (2 -d)
# ---------------------------------------------------------------------
import random
import numpy as np
import matplotlib . pyplot as plt

n = 10000
x = np . zeros (n )
y = np . zeros (n )
# ----------- filling the coordinates with random variables -----------
for i in range (1 , n):
  val = random . randint (1 , 4)
  if val == 1:
    x[i ] = x[i - 1] + 1
    y[i ] = y[i - 1]
  elif val == 2:
    x[i ] = x[i - 1] - 1
    y[i ] = y[i - 1]
  elif val == 3:
    x[i ] = x[i - 1]
    y[i ] = y[i - 1] + 1
  else :
    x[i ] = x[i - 1]
    y[i ] = y[i - 1] - 1
# ------------------ plottting the 2-d data ---------------------------
fig , ax = plt . subplots ()
plt . title (" Random Walk for 2-D ($n = " + str(n ) + "$ steps )")
ax . plot (x , y , '-k', ) # rand
ax . plot (x [1] , y [1] , 'go')
ax . plot (x[n -1] , y[n -1] , 'ro')
fig.set_figwidth(28)
fig.set_figheight(20)
plt . xlabel ("x corrdinates ") ; plt . ylabel ("y coordinates ")
plt . show ()
# ---------------------------------------------------------------------






Comments

Popular posts from this blog

Solving Kepler’s equation by Newton-Raphson method

Velapanti Python Program

Determining Wien’s constant using bisection method and false position method. (Python Program)