首页 > 解决方案 > 如何使变量属于范围 Netlogo

问题描述

我有一只乌龟,每次蜱虫可以吃不同量的食物,每次都会更新它的胃内容。我想将胃内容值四舍五入,使其属于范围 x。

这是更新胃内容物的草料功能:觅食

  ;; item=0.064g

  set patch-n random-float 100 
  if patch-n <= 8 [set stomach-content (stomach-content + 0.00) ] ; does not find any item
  if patch-n > 8 and patch-n <= 99 [set stomach-content (stomach-content + 0.192) ] ; finds 3 items
  if patch-n > 99 [set stomach-content 0.4 ]; full stomach

  ifelse stomach-content >= 0.132
  [set fat-reserves (fat-reserves + 0.132 ) set stomach-content (stomach-content - 0.132)]

  [set fat-reserves (fat-reserves + (stomach-content * 1)) set stomach-content 0] ;;
set fat-reserves (fat-reserves - (8 * bmr)) ; metabolic rate removes fat from fat reserves

end

我希望胃内容物属于的范围是

 set x (range 0 0.4 0.04)

有没有办法让我的胃含量值在这个有限的 11 个值范围内?

类似于在区间 (0 , 0.4) 中使用 mod=0.04 将胃内容物四舍五入到最接近的值

标签: rangeroundingnetlogointervals

解决方案


您可以对记者做一些花哨的事情mod,但如果您不需要它超快,以下内容很简单,也更灵活,因为它适用于任何值列表:

to-report nearest-in-list [ the-value the-list ]
  report first sort-by [ [a b] ->
    abs (a - the-value) < abs (b - the-value)
  ] the-list
end

然后你可以像这样使用它:

observer> show nearest-in-list 0.11 (range 0 0.4 0.04)
observer: 0.12
observer> show nearest-in-list 0.021 (range 0 0.4 0.04)
observer: 0.04
observer> show nearest-in-list 0.02 (range 0 0.4 0.04)
observer: 0

请注意,在平局的情况下(如0.02示例中的 with ,介于0和之间0.04),它会为您提供最低值。


推荐阅读