0

I'm trying to model a population where each year the population is either growing quickly or slowly, to a max size of 5000. I then am running this while loop 5000 times to look at variation in time to 5000.

However, the loop just keeps running, and I have to stop it manually.

One odd thing is that popVector, which is a vector that records the size of the population each round, grows to a tremendous size, often into the tens of thousands, which I would not predict from the numbers I'm using.

Any help to resolve this would be greatly appreciated!

MAXPOP <- 5000 #Set max population
trials <- 5000
genVector <- numeric(trials)
set.seed(1)

for(j in 1:trials) {
  curr_pop <- 20 #Set initial population
  genTime <- 1
  popVector <- curr_pop;
  while(curr_pop <= MAXPOP) {
    if(genTime%%2 == 0) {
      p <- 0.25
    }
    if(genTime%%2 != 0) {
      p <- 0.5
    }
    curr_pop <- sum(rgeom(curr_pop, p)) #Set current population
    popVector <- c(popVector, curr_pop)
    genTime <- genTime + 1
  }
  genVector[j] <- genTime
}
4

2 回答 2

1

The issue appears to be in your while loop. When I run the code curr_pop gets sets to zero on the 2826 iteration of your for loop. I"m not familiar enough with the rgeom function, but that's the place to investigate what would cause it to return a zero.

于 2013-09-20T22:18:39.100 回答
0

The rgeom function returns a vector of random numbers, with as many elements as the first argument. With a small first argument, and a second argument close to 1, it is a matter of time before it returns a set of all zeros, after which your curr_pop <- sum(rgeom(curr_pop, p)) will remain 0 forever.

You could work around that by wrapping that call in a while loop to check for 0 sum and resetting curr_pop to something else, for example:

while (T) {
    curr_pop <- sum(rgeom(curr_pop, p)) #Set current population
    if (curr_pop > 0) break
    else curr_pop <- 1
}

The iteration step 2826 mentioned by @Havik23 is because of the set.seed(1) call. This way always the same sequence of random numbers will be generated. If you want your program to be more random, you might want to comment out that call.

于 2013-09-20T22:48:54.373 回答