Get the mean age of all turtles on the time of death

有些话、适合烂在心里 提交于 2019-12-11 09:42:48

问题


I want to get the mean age of all dying turtles. I try to achieve that with the following code snipped:

globals [mean-death-age]
turtles-own [age prob-die?]

to-report mean-age
  if (prob-die? = true) [
    set mean-death-age mean [age] of turtles
  ]
  report mean-death-age
end

Every turtle has the probability of dying (prob-die?) which should be calculated new with every time step (tick). If prob-die? is set to true mean-death-age should be updated. At the moment I have the problem that

  • I don't know how to initiate the variable mean-death-age. Maybe, working with an if loop would help

    if (ticks >= 1) [    
      if (prob-die? = true) [
        set mean-death-age mean [age] of turtles
      ]
    ]
    
  • I don't get an update of the already calculated mean-death-age but the variable is overwritten and the mean death age of the turtles of this tick is returned

  • I have problems accesing the value. When I try to call it with e.g.

    print mean-age
    

    I get the error message that mean-age is turtle-only even though I tried to save is as a global variable.

The entire code is available here.


回答1:


I think you're making this more complicated than it needs to be. The easiest approach would be to just keep a list of ages at which turtles die, and then take the mean of that list:

globals [death-ages]
turtles-own [age]

to setup
  clear-all
  create-turtles 100 [
    setxy random-xcor random-ycor
    set age random 100
  ]
  set death-ages [] ; start with an empty list
  reset-ticks
end

to go
  if not any? turtles [ stop ]
  ask turtles [
    if random 100 < age [
      set death-ages lput age death-ages ; add age to our list of ages of death
      die
    ]
  ]
  print mean death-ages
  tick
end

The only downside is that your list of death-ages is going to keep growing as your model runs. If that turns out the be a problem (though it probably won't), you will need to keep track of the current average and the current count of observations and update your average with something like set avg ((n * avg) + age) / (n + 1) set n n + 1.

As for why your current code doesn't work, there would be a lot of unpacking to do to explain it all (I'm sorry I can't now). As a general comment, I would suggest trying to take a step back when you run into difficulties like this and think about the minimum amount of information that you need to solve the problem. In this case, you need to mean age of death. What the simplest way to get that? Keep a list of ages of death and take the mean of that list when needed­.



来源:https://stackoverflow.com/questions/49360142/get-the-mean-age-of-all-turtles-on-the-time-of-death

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!