Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. ## State x is number of points
  2. ## Each time period, either stop and enjoy utility u(X), or roll a six-sided die
  3. ## If roll a 6, lose everything, game ends, get u(0)
  4. ## If roll k < 6, move to state x' = x + k
  5.  
  6. max_x <- 30 # Maximum state to keep things simple -- in "true" problem this is infinite
  7. value <- rep(0, max_x)
  8.  
  9. utility <- function(x) {
  10. return(x) # Linear utility function
  11. }
  12.  
  13. n_iterations <- 100 # Value function iteration
  14. for(iteration in seq_len(n_iterations)) {
  15. value_next <- value
  16. for(x in seq_along(value)) {
  17. x_next_if_roll <- pmin(x + seq_len(5), max_x) # Next period's states if roll 1, 2, ... , 5
  18. value_next[x] <- max(utility(x), (1/6) * (utility(0) + sum(value[x_next_if_roll])))
  19. }
  20. distance <- mean(abs(value - value_next))
  21. value <- value_next
  22. message("iteration ", iteration, " value function distance ", round(distance, 4))
  23. if(distance < 10^-8) break
  24. }
  25.  
  26. max(which(value > seq_along(value))) # Last index at which it is optimal to keep playing
  27.  
  28. plot(value, type="b", xlab="state", ylab="value")
  29. abline(a=0, b=1, lty=2, col="red")
  30. abline(v=max(which(value > seq_along(value))) + 1, lty=2, col="grey") # Stop when reach this state
  31.  
  32. sum(value[1:5]) / 6 # Value before starting game (i.e. starting from state x=0): around 6.1537
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement