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

Python int()返回异常结果:自定义舍入函数的特殊场景问题

问题原因分析:浮点数精度与Pandas Series存储差异

这是二进制浮点数的精度局限性导致的,核心差异在于直接字面量583.065和Pandas Series中存储的该数值,在二进制层面的实际表示存在细微偏差:

  • 直接执行int(583.065*100+0.5)时,Python解释器对字面量583.065做了隐式精度优化,实际计算的是一个略大于58306.5的数值,加上0.5后超过58307,int()截断小数部分后得到预期的58307。
  • 但Pandas Series存储的583.065,是二进制浮点数无法精确表示的近似值(比如实际存储值可能是583.0649999999999),乘以100后得到58306.49999999999,加0.5后结果为58306.99999999999,int()截断时直接舍弃小数部分,最终得到58306。

验证代码

import pandas as pd

# 检查Series中存储的实际值
s = pd.Series([583.065])
print(s.iloc[0] == 583.065)  # 大概率返回False
print("{0:.20f}".format(s.iloc[0]))  # 显示实际近似值:583.06499999999993605093
print(int(s.iloc[0]*100 + 0.5))  # 输出58306

# 对比直接字面量的处理
print("{0:.20f}".format(583.065))  # 可能显示583.06500000000000000000(解释器优化结果)
print(int(583.065*100 + 0.5))  # 输出58307

解决方案

要避免这类精度问题,推荐两种可靠方式:

  1. 使用decimal模块做精确十进制计算
from decimal import Decimal, ROUND_HALF_UP

def custom_round(num):
    # 将数值转为字符串再构造Decimal,避免浮点数精度污染
    d = Decimal(str(num))
    # 四舍五入到两位小数后转整数
    return int(d.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) * 100)

s = pd.Series([583.065])
print(s.apply(custom_round))  # 输出58307
  1. 使用Pandas内置的round方法
s = pd.Series([583.065])
print((s.round(2)*100).astype(int))  # 输出58307

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 13:42:36