Babak Ravandi
Babak Ravandi

Reputation: 548

Netlogo Random Sampling with different probabilities

Is there a way in NetLogo to associate a probability value for each item in an array and randomly select n items? a function like below.

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"]

In Python numpy.random.choice exactly does this.

Upvotes: 3

Views: 424

Answers (1)

Bryan Head
Bryan Head

Reputation: 12580

This is exactly what the built-in rnd extension is for: https://ccl.northwestern.edu/netlogo/docs/rnd.html

rnd:weighted-n-of-list-with-repeats is the primitive you want. It's a little bit more flexible that numpy.random.choice, but also a little more cumbersome. You would write n-random-select like so:

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

and use it like so (remember, no commas in netlogo lists):

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"]

Upvotes: 5

Related Questions