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

二分法计算1年结清债务最低月还款额代码结果偏差排查求助

二分法计算年度结清债务最低月还款额 代码问题排查

问题说明

编写的代码用于计算1年内结清指定本金和年化利率债务的最低月还款额,在本金320000、年利率0.2的测试场景下输出29591.88,与官方参考结果29157.09存在明显偏差,核心问题如下:

代码错误点

  • 缺失二分法迭代循环:使用单次if判断替代了官方代码的while循环逻辑,二分法需要多次收缩上下限范围才能收敛到正确结果,单次计算完全无法满足精度要求,这是结果偏差的核心原因。
  • 变量拼写错误:判断条件中的remaningbalance拼写错误(正确拼写为remainingbalance),会直接触发运行时报错。
  • 中间计算提前截断精度:在每月计息环节、二分中间值计算环节都提前做了保留2位小数的取整操作,中间精度丢失会导致误差持续累积,官方代码仅在最终输出时做取整处理,中间计算保留完整浮点精度。
  • 精度阈值设置不合理:采用±0.01作为结束判断阈值,未考虑12个月计息后的误差传导,官方采用的0.03容错阈值更符合场景需求。

修正后代码示例

balance = float(input('balance  = '))
annualInterestRate = float(input('annualInterestRate = '))

init_balance = balance
monthlyInterestRate = annualInterestRate / 12
low = init_balance / 12
high = (init_balance * (1 + monthlyInterestRate) ** 12) / 12.0
epsilon = 0.03
increment = 0

while abs(balance) > epsilon:
    increment = (high + low) / 2
    balance = init_balance
    for i in range(12):
        unpaid = balance - increment
        interest = monthlyInterestRate * unpaid
        balance = unpaid + interest
    if balance > epsilon:
        low = increment
    elif balance < -epsilon:
        high = increment

print('Lowest Payment: ', round(increment, 2))

验证结果

上述修正代码在本金320000、年利率0.2的测试场景下,输出结果为29157.09,与官方参考代码结果一致。

内容的提问来源于stack exchange,提问作者Syed Ali Ahmed Islam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:30:00