Advertisement
juaniisuar

ej4 tproba

Jul 2nd, 2017
347
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. library("markovchain")
  2.  
  3. matrix.power <- function(A, n) {
  4. if(n == 0)
  5. return(diag(dim(P)[1]))
  6. e <- eigen(A)
  7. M <- e$vectors
  8. d <- e$values
  9.  
  10. if(length(M) == dim(P)[1]) # si es diagonalizable
  11. return(M %*% diag(d^n) %*% solve(M))
  12. else{
  13. newA = diag(dim(P)[1])
  14. for(i in 1:n)
  15. newA = newA %*% A
  16. return(newA)
  17. }
  18. }
  19.  
  20. S = c("A", "B", "C", "D")
  21.  
  22. mu0 = c(1/8, 2/8, 1/8, 4/8)
  23.  
  24. P = matrix(
  25. c(0.1, 0.1, 0.8, 0,
  26. 0.4, 0 , 0.5, 0.1,
  27. 0.1, 0 , 0 , 0.9,
  28. 0.4, 0.1, 0.5, 0),
  29. nrow = 4,
  30. ncol = 4,
  31. byrow = TRUE
  32. )
  33.  
  34. if( sum(mu0) != 1 ) #el vector de distrib. inicial k debe sumar 1
  35. stop( "Las probabilidades del vector inicial no suman 1" )
  36.  
  37. for(i in 1:dim(P)[1]){
  38. if( sum (P[i,]) != 1) #las filas deben sumar 1
  39. stop( "Las filas individuales de P no suman 1" )
  40.  
  41. if( P[i,i] == 1 ) #no debe haber estados absorbentes por enunciado
  42. stop( "Hay algún estado absorbente presente" )
  43. }
  44.  
  45. Q = new("markovchain", transitionMatrix = P,
  46. states = S, name = "Buffer")
  47.  
  48. plot(Q, main = "Cadena de Markov", edge.arrow.size=0.5)
  49.  
  50. #simulate
  51. tests=10000
  52. n = 20
  53.  
  54. for(i in 1:tests){
  55. T = markovchainSequence(n, M, t0 = sample(Q@states, prob = mu0, replace = TRUE, 1), include.t0 = TRUE)
  56. if(i==1){
  57. K = table(T)
  58. plot(0:n, factor(T), yaxt = "n", main = "Simulación de una Trayectoria", ylab = "Estado", xlab = "Tiempo", type = "l", col = "blue")
  59. axis(side=2, at = 1:4, labels = S)
  60. } else {
  61. L = table(T)
  62. u <- intersect(names(K), names(L))
  63.  
  64. res <- c(K[!(names(K) %in% u)], L[!(names(L) %in% u)], K[u] + L[u])
  65.  
  66. K = res[order(names(res))]
  67. }
  68. }
  69. K = K / tests
  70.  
  71. #newP = P^n
  72. newP = matrix.power(P, n)
  73. muN = mu0 %*% newP #probabilidad de estar en el i-esimo nodo luego de 'n' pasos
  74.  
  75. print("Promedio de visitas a los nodos (en n=20 pasos) simulada: ")
  76. print(K)
  77. print("Cantidad teorica de visitas a los nodos (en n=20 pasos): ")
  78. print(muN*n)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement