Python列表元素求和趋近15的代码逻辑错误排查求助
问题排查
1. 根因:浮点数二进制存储精度误差
你的代码逻辑完全匹配你描述的遍历规则,结果不符合预期的核心原因是Python默认的浮点数采用二进制编码存储,绝大多数十进制小数无法被精确表示,多次累加后会产生微小的精度偏差。
手动校验你的累加规则可得理论值确实为14.9,但实际代码运行后得到的是14.899999999999999,和14.9数值几乎等价,只是显示形式不符合预期。
2. 可优化细节
你预先定义了阈值变量income = 15,但判断条件里硬编码写死了数值15,没有复用该变量,后续调整阈值需要修改两处,容易引发逻辑不一致问题。
修复方案
方案1:输出时格式化处理
如果仅需要显示结果为14.9,直接对输出结果做精度处理即可:
# 方式1:四舍五入保留1位小数 print(round(total, 1)) # 方式2:格式化输出保留1位小数 print("{:.1f}".format(total))
方案2:使用十进制精确计算
如果需要全程无精度误差,可以使用Python内置的decimal模块做十进制精确运算:
from decimal import Decimal list1 = [ [Decimal('5.0'), Decimal('1.3'), Decimal('6.6'), Decimal('5.076923076923077')], [Decimal('9.0'), Decimal('1.5'), Decimal('7.0'), Decimal('4.666666666666667')], [Decimal('4.0'), Decimal('1.0'), Decimal('4.0'), Decimal('4.0')], [Decimal('3.0'), Decimal('2.0'), Decimal('5.5'), Decimal('2.75')], [Decimal('7.0'), Decimal('1.6'), Decimal('3.5'), Decimal('2.1875')], [Decimal('2.0'), Decimal('1.7'), Decimal('3.5'), Decimal('2.058823529411765')], [Decimal('1.0'), Decimal('3.0'), Decimal('6.0'), Decimal('2.0')], [Decimal('6.0'), Decimal('1.0'), Decimal('2.0'), Decimal('2.0')], [Decimal('8.0'), Decimal('2.5'), Decimal('5.0'), Decimal('2.0')], [Decimal('10.0'), Decimal('1.8'), Decimal('1.0'), Decimal('0.5555555555555556')] ] income = Decimal('15') total = Decimal('0') for i in list1: if total + i[1] <= income: total += i[1] print(total)
运行后可直接得到精确的14.9结果。
内容的提问来源于stack exchange,提问作者codegeek
相关产品推荐
相关产品推荐

