NetLogo中计算匹配变量海龟意见平均值时MEAN函数报错求助
NetLogo模型错误修复:计算同区域海龟变量平均值
问题说明
运行模型setup时触发错误:
MEAN expected input to be a list but got the number #### instead.
(注:####为每次运行时随机变化的浮点数)
模型执行流程:
- 定义
districts种群,生成地图上不同颜色的区域。 - 创建
turtles:随机分配opinion值、linked(0或1),并获取所在patch对应的district实例存入mydistrict变量。 - 调用
org-effects-mean过程,意图计算同区域内所有linked=1的海龟的opinion平均值,赋值给海龟的org-influence-opinion变量,但该过程触发上述错误。
错误原因
org-effects-mean过程的写法逻辑错误:
set org-influence-opinion ([ mean opinion ] of turtles with [mydistrict = [mydistrict] of myself and linked = 1])
这段代码是让每个符合条件的海龟分别执行mean opinion操作,但单个海龟的opinion是单个数值,并非列表,而MEAN原语要求输入必须是列表,因此触发错误。
解决方案
正确逻辑是先获取所有符合条件的海龟的opinion值组成的列表,再对列表求平均值。调整org-effects-mean过程写法如下:
to org-effects-mean ask turtles [ if linked = 1 [ let target-turtles turtles with [mydistrict = [mydistrict] of myself and linked = 1] set org-influence-opinion mean [opinion] of target-turtles ] ] end
代码解释
- 用
let target-turtles筛选出当前海龟所在区域、且linked=1的所有海龟集合。 - 用
[opinion] of target-turtles提取这些海龟的opinion值,得到数值列表。 - 对列表执行
mean计算,将平均值赋值给org-influence-opinion。
修正后的完整代码
breed [ districts district ] turtles-own [ linked mydistrict opinion org-influence-opinion ] districts-own [ district-id district-patches district-turtles ] patches-own [ pdistrict ] globals [ num-districts ] to setup ca set num-districts 4 grow-districts create-turtles 100 ask turtles [ setxy random-xcor random-ycor set linked one-of [ 0 1 ] set mydistrict [pdistrict] of patch-here set opinion random-float 1 ] org-effects-mean end to grow-districts ;; Barranca addition Create-districts num-districts [ ;; set district breed shape set shape "arrow" __set-line-thickness 1 set size .4 ;; Set randomish location... setxy random-xcor random-ycor ;;; tag this patch Set pdistrict self ;set district-id district-id + 1 set color (deep-color-1 who) set pcolor color ] ;; expand districts While [ any? patches with [ pdistrict = 0 ] ] [ Ask patches with [ pdistrict != 0 and any? Neighbors with [ pdistrict = 0 ] ] [ Ask neighbors with [ pdistrict = 0 ] [ set pdistrict [ pdistrict] of myself Set pcolor [ color ] of pdistrict ] ] ] end to org-effects-mean ask turtles [ if linked = 1 [ let target-turtles turtles with [mydistrict = [mydistrict] of myself and linked = 1] set org-influence-opinion mean [opinion] of target-turtles ] ] end to-report deep-color-1 [ value ] report ( red + 10 * (value mod 13) ;; base netlogo color ;; shift up or down + .5 * ( (int (value / 13 )) mod 2 * 2 - 1) ;; alternate normal -1, +1 ;; increase difference (gets brighter and darker) * (1 + int ( value / ( 2 * 13 ))) ) end
内容的提问来源于stack exchange,提问作者Abe
相关产品推荐
相关产品推荐

