首页 > 解决方案 > 如何计算 Netlogo 中分母有时为零的百分比?

问题描述

我正在尝试将变量设置为代理集中的代理集的百分比。因此,程序有时会尝试除以零,我收到一条错误消息。

我尝试使用 ifelse 条件,以便仅在分母大于 0 时运行该位代码。但是,我仍然收到错误消息。我在以下代码中遗漏了什么吗?

ifelse any? people with [recentvent? and trait = 1] 
[set %minority-affiliated-vents 100 * (count people with [groupid > 0 and recentvent? and trait = 1] / count people with [recentvent? and trait = 1])]
[set %minority-affiliated-vents 0]

我仍然得到零运行时错误的除法。

标签: netlogopercentagedivide-by-zero

解决方案


我看不出你的代码有什么问题。作为一般方法,您可以按如下方式修改您的代码 - 这减少了您需要构建代理集的次数,但也确保您不会意外地在测试和用作分母之间以不同的方式构建它。它也更容易阅读。

let test-agentset people with [recentvent? and trait = 1] 
ifelse any? test-agentset 
[set %minority-affiliated-vents 100 * count test-agentset with [groupid > 0] / count test-agentset]
[set %minority-affiliated-vents 0]

通过这种构造,您可以看到分母不能为零,因此错误必须在代码中的其他位置。


推荐阅读