Skip to content

Instantly share code, notes, and snippets.

@MLWhiz
Created June 3, 2019 17:46
Show Gist options
  • Save MLWhiz/d02fa61e3ef841340de64417c4e35c31 to your computer and use it in GitHub Desktop.
Save MLWhiz/d02fa61e3ef841340de64417c4e35c31 to your computer and use it in GitHub Desktop.
import random
# Lets define our Beta Function to generate s for any particular state. We don't care for the normalizing constant here.
def beta_s(w,a,b):
return w**(a-1)*(1-w)**(b-1)
# This Function returns True if the coin with probability P of heads comes heads when flipped.
def random_coin(p):
unif = random.uniform(0,1)
if unif>=p:
return False
else:
return True
# This Function runs the MCMC chain for Beta Distribution.
def beta_mcmc(N_hops,a,b):
states = []
cur = random.uniform(0,1)
for i in range(0,N_hops):
states.append(cur)
next = random.uniform(0,1)
ap = min(beta_s(next,a,b)/beta_s(cur,a,b),1) # Calculate the acceptance probability
if random_coin(ap):
cur = next
return states[-1000:] # Returns the last 100 states of the chain
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment