首页 > 解决方案 > 距离期望输入成为代理,但没有人代替

问题描述

NetLogo 中出现错误,代码如下。我想做的是让每只乌龟检查最近的乌龟并计算我自己(乌龟)和它最近的乌龟之间的距离。

如果距离小于 8,则乌龟不满意,否则,乌龟变得满意。不满意的乌龟死了。

在某些时候,周围只有一只乌龟,所以“最近的”乌龟是无名小卒。它无法计算到不存在的海龟的距离。我知道出了什么问题,我尝试用一​​段代码来解决它,如果周围没有人,将海龟的满意度设置为 0(真)。但我仍然得到消息:距离预期输入是代理但没有人代替..

你能看出哪里出了问题吗?

ask turtles [ let nearest min-one-of turtles [ distance myself ] 
    ifelse nearest = nobody 
    [ set satisfaction 1 ]
    [ ifelse distance nearest < 8 [ set satisfaction 0] [ set satisfaction 1 ] ] ]

标签: inputnetlogoagentagent-based-modeling

解决方案


请编辑您的问题,而不是提供跟进作为答案。

问题是您混淆了您的满意度值。您在问题文本中声明 0 表示满意,但如果nearest != nobody(即有另一个代理)则分配 1。nearest != nobody因此,当为假时或等效地,当最近的实际上是无人时,您的代码会跳转到距离计算块。所有这些都可以通过使用trueand来避免false,这将使您的代码更易于阅读并且不易出错。这不是必需的,但 NetLogo 约定有一个 ? 在用于布尔(真/假)变量的变量名称的末尾。

所以,重写你的代码使它可以独立并放弃 0/1,转储负测试(这很令人困惑)并反转最终分配,它看起来像这样:

turtles-own [satisfied?]

to testme
  clear-all
  create-turtles 20
  [ setxy random-xcor random-ycor
  ]
  ask turtles
  [ if any? other turtles 
    [ let nearest min-one-of (other turtles) [distance myself] 
      ifelse nearest = nobody
      [ set satisfied? true ]
      [ ifelse distance nearest < 8 
        [ set satisfied? false ]
        [ set satisfied? true ] 
      ]
    ]
  ]
  type "satisfied turtles: " print count turtles with [satisfied?]
end

我还重新格式化了代码,这样你就可以看到你的ifelse结构在哪里运行。现在也很清楚,没有赋值给满意?如果只有一只海龟,则该值将保持为默认值 0。

所以更好的版本看起来像:

ask turtles
[ ifelse any? other turtles 
  [ let nearest min-one-of (other turtles) [distance myself]
    ifelse distance nearest < 8 
    [ set satisfied? false ]
    [ set satisfied? true ] 
  ]
  [ set satisfied? true
  ]
]

这可以在一个单一的声明中完成(我已经积极而不是消极地表达了它,因为这更容易阅读,所以也请参阅新not声明):

to testme
  clear-all
  create-turtles 1
  [ setxy random-xcor random-ycor
  ]
  ask turtles
  [ ifelse not any? other turtles or
           distance min-one-of (other turtles) [distance myself] > 8
    [ set satisfied? true ]
    [ set satisfied? false ] 
  ]
  type "satisfied turtles: " print count turtles with [satisfied?]
end

您需要对子句进行排序,以便它检查第any?一个。这应该通过嵌套ifelse在您尝试的解决方案中来实现,除非您颠倒了测试。


推荐阅读