NetLogo : How to make sure a variable stays in a defined range?

前端 未结 3 695
盖世英雄少女心
盖世英雄少女心 2020-12-06 03:29

I have a few variables which can be inherited to child agents by a variation of + 0.1 and -0.1 or without any changes, or random again, What I have done is like this: (The

3条回答
  •  爱一瞬间的悲伤
    2020-12-06 03:54

    As you've discovered, random-normal can be problematic because the result you get back can be literally any number.

    One possible solution is to clamp the output of random-normal within boundaries, as in Matt's answer. Note that this approach creates spikes at the boundaries of the range:

    observer> clear-plot set-plot-pen-interval 0.01 set-plot-x-range -0.1 1.1
    observer> histogram n-values 1000000 [ median (list 0 (random-normal 0.5 0.2) 1) ]
    

    enter image description here

    Another possible solution, as Marzy describes in the question itself, is to discard any out-of-bounds results random-normal gives you and just keeping trying again until you get an in-bounds result. This avoids the spikes at the boundaries:

    to-report random-normal-in-bounds [mid dev mmin mmax]
      let result random-normal mid dev
      if result < mmin or result > mmax
        [ report random-normal-in-bounds mid dev mmin mmax ]
      report result
    end
    
    observer> clear-plot set-plot-pen-interval 0.01 set-plot-x-range -0.1 1.1
    observer> histogram n-values 1000000 [ random-normal-in-bounds 0.5 0.2 0 1 ]
    

    enter image description here

    Another solution is to ask yourself whether you really need a bell curve, or whether a triangle-shaped distribution would be just fine. You can get a triangle-shaped distribution of results very simply just by summing two calls to random-float:

    observer> clear-plot set-plot-pen-interval 0.01 set-plot-x-range 0 1
    observer> histogram n-values 10000000 [ 0.5 + random-float 0.5 - random-float 0.5 ]
    

    histogram

提交回复
热议问题