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

如何调整度分秒与十进制度互转函数的小数精度以通过指定断言测试

度分秒与十进制度互转函数修复方案

问题根源

原实现存在两个核心问题导致断言失败:

  1. degrees_to_dms逻辑错误:计算分钟时未取整,且对秒做了仅保留2位小数的四舍五入,直接截断了精度,导致转换得到的dms元组自带误差
  2. 冗余浮点转换:dms_to_degrees中多余的float强制转换,叠加分步浮点运算的精度损耗,出现了0.2833333332999999这类不符合预期的末尾误差

修复后代码

def degrees_to_dms(degrees_fraction):
    ''' Convert degrees to degree, minute, second 3-tuples'''
    degrees = int(degrees_fraction)
    remainder = abs(degrees_fraction - degrees)
    # 先对分钟取整,避免误差传递到秒的计算
    minutes = int(remainder * 60.0)
    # 秒保留足够小数位,不要强行截断为2位
    seconds = round((remainder * 60.0 - minutes) * 60.0, 10)
    # 适配负度数场景,符号统一落在度的数值上
    if degrees_fraction < 0:
        degrees = -abs(degrees)
    return (degrees, abs(minutes), abs(seconds))


def dms_to_degrees(d,m,s):
    ''' Convert degrees, minutes, seconds to fractional degrees'''
    # 去掉冗余float转换,减少精度损失
    return d + m/60.0 + s/3600.0

如果需要保留原代码的numpy依赖,把round替换为np.round即可,效果一致。

验证

运行给定测试断言可直接通过:

assert dms_to_degrees(*degrees_to_dms(42.2833333333)) == 42.28333333333333

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:45:03