title: Implementing the metropolis-hasting algorithm
body: <p>Over the past few weeks I have been trying to understand MCMC and the Metropolis-Hastings, but I have failed every time I tried to implement it.  </p>
  
  <p>So I am trying to use the metropolis-Hastings algorithm to get the Boltzmann distribution from the uniform distribution, but it is not working. </p>
  
  <p>Here is a summary of what I am doing: </p>
  
  <ol>
  <li>I draw a random number form the uniform distribution m.</li>
  <li>I draw another random number form the uniform distribution n.</li>
  <li>I set dU = n-m.</li>
  <li>If dU &lt; 0, I accept dU, set m = n , and repeat.</li>
  <li>If dU > 0, I calculate w = exp(-b*dU), where b is 1/kT, and draw a random number form the uniform distribution r.</li>
  <li>If w > r, I accept dU, set m = n, and repeat.
  7 If w &lt; r, I reject dU, set m = m, and repeat.</li>
  </ol>
  
  <p>I am a beginner to this field and to python, so I am not sure if the code  wrong or the algorithm is wrong ( probably both.)  </p>
  
  <p>My code is attached below. Thank you.</p>
  
  <pre><code>import random
  %matplotlib inline
  import numpy as np
  import scipy
  import matplotlib.pyplot as plt
  from scipy import stats
  k = 1.38064852 * 10**(-23)
  t = 298
  b = 1/(t*k)   U = []
  m = np.random.uniform(0, 1)
  for j in range(100000):
      n = np.random.uniform(0, 1)
      du = n-m
      if du&lt;0:
              U.append(du)
              m = n 
      elif du &gt; 0:
              w = np.exp(-b*du)
              r = np.random.uniform(0, 1)
              if w &gt; r:
                      U.append(du)
                      m = n
              else:
                      U.append(du)
                      m = m
  </code></pre>