NetLogo中有没有一种方法可以为数组中的每个项目关联一个概率值并随机选择n个项目?如下所示的函数。
let names ["pooh", "rabbit", "piglet", "Christopher"]
let probs [0.5, 0.1, 0.1, 0.3]
n-random-select 5 names probs
>>["pooh", "pooh", "pooh", "Christopher", "piglet"]
在Python中numpy.random.choice
正是这样做的。
最佳答案
这正是内置 rnd
扩展的用途:https://ccl.northwestern.edu/netlogo/docs/rnd.html
rnd:weighted-n-of-list-with-repeats
是你想要的原语。它比 numpy.random.choice 更灵活一些,但也更麻烦一些。您可以像这样编写n-random-select
:
to-report n-random-select [ n xs weights ]
report map first rnd:weighted-n-of-list-with-repeats n (map list xs weights) last
end
像这样使用它(记住,netlogo列表中没有逗号):
observer> show n-random-select 5 ["pooh" "rabbit" "piglet" "Christopher"] [0.5 0.1 0.1 0.3]
observer: ["pooh" "pooh" "pooh" "Christopher" "Christopher"]
observer> show n-random-select 5 ["pooh" "rabbit" "piglet" "Christopher"] [0.5 0.1 0.1 0.3]
observer: ["pooh" "Christopher" "Christopher" "Christopher" "Christopher"]
observer> show n-random-select 5 ["pooh" "rabbit" "piglet" "Christopher"] [0.5 0.1 0.1 0.3]
observer: ["rabbit" "rabbit" "rabbit" "piglet" "Christopher"]
关于random - Netlogo 不同概率的随机采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50878873/