Last active
April 8, 2018 18:29
-
-
Save slwu89/5d95cd95cccfb174a7048a0363109427 to your computer and use it in GitHub Desktop.
simple example of using a gillespie algorithm to simulate a ctmc with 2 events
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
events = c( | |
birth = 1/1.5, | |
death = 1/2.5 | |
) | |
state = c( | |
animals = 5 | |
) | |
tmax = 1e3 | |
t = 1 | |
i = 2 | |
while(t[length(t)] <= tmax){ | |
birth_rate = state[i-1] * events[["birth"]] | |
death_rate = state[i-1] * events[["death"]] | |
overall_rate = birth_rate + death_rate | |
# sample when the thing happens | |
t[i] = t[i-1] + rexp(n = 1,rate = overall_rate) | |
# sample what happens | |
what = sample(x = c(1,2),size = 1,prob = c(birth_rate,death_rate)) | |
if(what==1){ | |
state[i] = state[i-1] + 1 | |
} | |
if(what==2){ | |
state[i] = state[i-1] - 1 | |
} | |
if(state[i]==0){ | |
break() | |
} | |
} | |
# plot(state,type="l") | |
plot(x = t,y = state,type="l") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment