NetLogo 6.3运行5.2版本行人模型报错:数学运算产生非数值
解决NetLogo 6.3运行旧行人模型的“数学运算产生非数值”错误
错误原因
- 变量未初始化:部分patch的
elevation变量未被正确赋值,NetLogo 6.x对未定义变量的处理比5.2更严格,直接参与运算会返回非数值。 - 空集合处理:当海龟处于世界边缘时,
neighbors集合为空,min-one-of无法对空集合执行计算,触发错误。 - 潜在数值溢出:原代码中
9999999的权重过大,可能导致数值超出NetLogo的处理范围。
修复步骤
1. 确保所有patch的elevation初始化
在模型的setup过程中添加初始化逻辑,确保没有patch的elevation处于未定义状态:
ask patches [ ; 根据原模型逻辑设置默认值,这里假设默认海拔为0,可自行调整 if elevation = undefined [ set elevation 0 ] ]
2. 处理边缘海龟的空邻居集合
修改go过程中获取target的代码,先判断邻居是否存在,再执行计算:
ask turtles [ set moved? false let target nobody ; 仅当有邻居时才计算目标patch if any? neighbors [ set target min-one-of neighbors [ elevation + ( count turtles-here * 1000) ] ; 降低权重避免溢出 ] ; 使用target前先检查是否有效 if target != nobody and [elevation + (count turtles-here * 1000)] of target < [elevation] of patch-here [ face target move-to target set moved? true ask target [set path path + 1] ] ]
3. 优化其他细节(可选)
- 简化
move-speed的计算:set move-speed count turtles with [moved?] / count turtles(6.x支持直接判断布尔变量,无需= true) - 检查
path变量是否被正确初始化,避免后续颜色计算出错。
修改后的完整go过程
to go if count turtles > 0 [set move-speed count turtles with [moved?] / count turtles] if count turtles = 0 [stop] ask patches with [exit = 1] [ask turtles-here[die]] ask turtles [ set moved? false let target nobody if any? neighbors [ set target min-one-of neighbors [ elevation + ( count turtles-here * 1000) ] ] if target != nobody and [elevation + (count turtles-here * 1000)] of target < [elevation] of patch-here [ face target move-to target set moved? true ask target [set path path + 1] ] ] if Show_path? [ask patches with [elevation < 9999999][let thecolor (9.9 - (path * 0.15)) if thecolor < 0.001 [set thecolor 0.001] set pcolor thecolor]] tick end
内容的提问来源于stack exchange,提问作者Mark
相关产品推荐
相关产品推荐

