You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

simulate_infection函数计算结果与预期差1的问题排查求助

问题修复:感染模拟函数计算差1的原因及解决办法

核心问题

你当前代码的新增感染数取整方式错误:函数要求每日新增感染数向上取整,但你用了round()(四舍五入),导致关键步骤的数值计算偏差1。

以传入的参数为例:
第1天感染数是13,计算第2天新增感染数时,13 * 1.7300982536113874 ≈ 22.491,round()得到22,但向上取整应该是23——这直接导致第2天累计死亡数少加1,最终第3天的存活种群数就比预期多1。

修复后的代码

import math

def simulate_infection(population, initial_infected, r_number):
    infected = initial_infected
    deceased = 0
    day = 1
    print(day, population)
    alive = population
    while alive > 0:
        # 累加当日死亡数
        deceased += infected
        # 计算次日感染数,向上取整
        infected = math.ceil(infected * r_number)
        day += 1
        alive = population - deceased
        print(day, alive)

验证修复结果

传入参数(322802, 13, 1.7300982536113874)后:

  • 第1天输出:1 322802
  • 第2天:累计死亡13,存活322789,输出2 322789
  • 第3天:累计死亡13+23=36,存活322802-36=322766,完全符合预期。

内容的提问来源于stack exchange,提问作者Zparm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 01:14:53