title: 1D Random Walk from Matlab to Python
body: <p>I have a Matlab code that generates a 1D random walk. </p>
  
  <pre><code>%% probability to move up or down
  prob = [0.05, 0.95];
  
  start = 2;  %% start with 2
  positions(1) = start; 
  
  for i=2:1000 
      rr = rand(1); 
      down = rr&lt;prob(1) &amp; positions(i-1)&gt;1;  
      up = rr&gt;prob(2) &amp; positions(i-1)&lt;4;  
      positions(i) = positions(i-1)-down + up; 
  figure(1), clf
  plot(positions)
  </code></pre>
  
  <p>This gives me the plot below <a href="http://i.stack.imgur.com/URx9o.png" rel="nofollow">1D Random Walk with Matlab</a></p>
  
  <p>I need to try to translate this in Python and I have came up with this (using numpy):</p>
  
  <pre><code>import random
  import numpy as np
  import matplotlib.pyplot as plt
  
  prob = [0.05, 0.95]  ##probability to move up or down
  N = 100 ##length of walk
  
  def randomWalk(N):
      positions=np.zeros(N)
      start = 2 ##Start at 2
      positions[0] = start
      for i in range(1,100):
          rr = random.randint(0,1)
  
          if rr&lt;prob[0] and positions[i-1]&gt;1: 
              start -= 1
          elif rr&gt;prob[1] and positions[i-1]&lt;4:
              start += 1
          positions[i] = start
      return positions
  
  plt.plot(randomWalk(N))
  plt.show()
  </code></pre>
  
  <p>It looks fairly close to what I want (see figure below):<a href="http://i.stack.imgur.com/Q476o.png" rel="nofollow">1D Random Walk with Python</a></p>
  
  <p>But I wonder if they are really equivalent, because they do seem different: The Python code seems spikier than the Matlab one.  </p>
  
  <p>What is missing in my Python code to achieve the perfect stepwise increase/decrease (similar to the Matlab code)? Maybe it needs an "else" that tells it to stay the same unless the two conditions are met. How do I implement that?</p>