Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- BURN_IN = 10000
- DRAWS = 100000
- f = function(x) exp(sin(x))
- chain = numeric(BURN_IN + DRAWS)
- x = 1/2
- for (i in 1:(BURN_IN + DRAWS)) {
- y = runif(1) # proposal
- if (runif(1) < min(1, f(y)/f(x))) x = y
- chain[i] = x
- }
- x_min = median(chain[BURN_IN : (BURN_IN + DRAWS)])
- cat("Metropolis minimum found at", x_min, "nn")
- # MONTE CARLO ENDS HERE. The integrations bellow are just to check the results.
- A = integrate(f, 0, 1)$value
- F = function(x) (abs(integrate(f, 0, x)$value - A/2))
- cat("Optimize minimum found at", optimize(F, c(0, 1))$minimum, "n")
- Metropolis minimum found at 0.6005409
- Optimize minimum found at 0.601365
Add Comment
Please, Sign In to add comment