vendredi 27 janvier 2017

Netlogo: Assign variable using probabilities

How to assign a string or integer variable to turtle, using probabilities of the variables in a group/list? For example it is 0.4 probability that one specific variable is used from specific group/list. The function selects randomly the variable based on probability. I need to use the same method afterwards to choose a variable (string) from a list according to probability. In python it should be:

import random
def random_value(probability_list, values):
    r = random.random()
    index = 0
    while(r >= 0 and index < len(probability_list)):
      r -= probability_list[index]
      index += 1
    value=values[index - 1]
    value_index=index-1
    return value,value_index

I tried it in Netlogo like below (get error that index is -1) but is there a better way?

globals [random_nr probabilities some_list index]
to initialize-variables
  set some_list[]
  set probabilities[]
end
to random_pick
  set random_nr random-float 1
  set probabilities [0.1 0.2 0.4 0.3]
  set some_list ["String1" "String2" "String3" "String4"]
  set index 0
  while [(random_nr >= 0) and (length probabilities < index)] [
   set random_nr random_nr - item index probabilities
   set index index + 1 ]
  set index index - 1
end




Aucun commentaire:

Enregistrer un commentaire