关于这个问题(NetLogo - no more than 5 % of population has a certain value of variable),我想将一个二进制变量随机分配给一个总体,其中5%或更少的总体中变量var
的值为0。
让我们考虑以下代码段:
ifelse var = 0 [ ] ; if var already 0, do nothing
[ ask n-of random 6 turtles [ set var 0 ] ] ; otherwise take random turtles and assign 0 to their var
if number-novar > (count turtles * 0.05) [ ;; check if more then 5 % are with var = 0
let %N (abs (count turtles * 0.05) - number-novar) ;; count number of turtles with var = 0, subtract from 5 % of the total turtles
ask n-of (1 + random %N) turtles [ set var 0 ] ;; set random number turtles with var = 0 (less than or equal to 5 % of total population)
]
每个刻度,代码将检查有多少只乌龟有var = 0
。如果目前的var = 0
龟总数中只有不到5%,则会将随机数量的龟分配给var = 0
,因此{{ 1}}。
例如,如果在第1个滴答处有100只海龟,其中1只具有var = 0
,则代码可以随机分配0至4只海龟,并带有var = 0
。如果5个龟有var = 0
,而当前的总数是100,则代码不会分配任何具有该值的龟。如果当前总种群在第2跳到第2跳之间增加,共有1只具有var = 0
的海龟,则允许该代码为var = 0
随机分配0到9只海龟,其值为0。
上面的代码中某处有一个错误,因为它在第2或3滴答之后几乎分配了var
的总人口,但是我找不到错误。
答案 0 :(得分:1)
由于您的代码中包含ifelse var = 0 [ ]
,因此我假设该代码由ask turtles
调用。如果是真的,您的var = 0
乌龟什么也不做,但是所有其他乌龟都会要求其他6只乌龟将其var设置为0。请看下面的玩具模型,该示例保持5%的var = 0的海龟(注释中有更多详细信息):
turtles-own [ var ]
to setup
ca
crt 100 [
set var 1
]
ask n-of ( count turtles * 0.05 ) turtles [
set var 0
]
reset-ticks
end
to go
decay
print ( word "After decay, there are " count turtles with [ var = 0 ] " turtles with var 0" )
maintain-5%
print ( word "After maintenance, there are " count turtles with [ var = 0 ] " turtles with var 0" )
tick
end
to decay
; Randomly have some var 0 turtles switch to var 1
ask turtles with [ var = 0 ] [
if random-float 1 < 0.2 [
set var 1
]
]
end
to maintain-5%
; Get a count of turtles with var 0, and 5% of the current turtle count, and the different
let n-novar count turtles with [ var = 0 ]
let max-novar ( count turtles * 0.05 )
let dif max-novar - n-novar
; If n-novar is less than the max, ask 'dif' turtles with var 1 to switch to var 0
if n-novar < max-novar [
ask n-of dif turtles with [ var = 1 ] [
set var 0
]
]
end