input - 距离期望输入成为代理,但没有人代替
问题描述
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 ] ] ]
解决方案
请编辑您的问题,而不是提供跟进作为答案。
问题是您混淆了您的满意度值。您在问题文本中声明 0 表示满意,但如果nearest != nobody
(即有另一个代理)则分配 1。nearest != nobody
因此,当为假时或等效地,当最近的实际上是无人时,您的代码会跳转到距离计算块。所有这些都可以通过使用true
and来避免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
在您尝试的解决方案中来实现,除非您颠倒了测试。
推荐阅读
- c - 将 Quake 2 中的 MASM5 代码移植到 GAS——意外的渲染结果
- spring - 如何使用 web.xml 和错误控制器配置 JSON 格式的 Spring 错误页面
- android - 在 Android 的底页顶部添加图像
- tmux - 用于在 tmux 中配置多行状态行的状态格式设置
- reactjs - 使用 ReactDOM.render 将链接添加为路由器的子节点会产生“您不应该在
" - excel - 在 Excel 中为列建立索引
- java - 使用 Travis-CI 和 Gradle 时从 getResourceAsStream 获取 null
- r - 通过列名命名列表中的数据框
- machine-learning - 在 Cifar10 上训练 GAN 时的异常损失曲线
- anylogic - 我们如何在anylogic中添加基于参数或代理颜色的图表?(无代理状态)