如何为NetLogo中每只海龟单独保存其与最近海龟的距离变量?
解决NetLogo计算最近海龟距离的问题
你的代码问题在于:min-one-of turtles [distance myself]返回的是距离当前海龟最近的海龟代理对象,而非距离数值,所以无法直接赋值给distance变量;同时turtles集合包含当前海龟本身,会导致计算出的最小距离为0(到自身的距离),这通常不符合需求。
修正后的代码有两种实现方式:
方式1:先获取最近海龟再计算距离
let nearest-turtle min-one-of other turtles [distance myself] set distance distance nearest-turtle
方式2:直接计算最小距离
set distance min [distance myself] of other turtles
额外建议
- 使用
other turtles排除当前海龟,避免计算自身距离 - 变量名
distance和NetLogo内置的distance命令重名,虽然语法允许,但容易混淆,建议改为nearest-distance这类更清晰的名称,示例:
set nearest-distance min [distance myself] of other turtles
内容的提问来源于stack exchange,提问作者Yolom
相关产品推荐
相关产品推荐

