pythonunittest2assertAlmostEqual 与 `places` 工作不正确

标签 python unittest2

我正在使用 unittest2 处理以下问题:

assertAlmostEqual(69.88, 69.875, places=2)  # returns True

但是

assertAlmostEqual(1.28, 1.275, places=2)  # returns False

我认为问题出在 assertAlmostEqual 方法中:

def assertAlmostEqual(self, first, second, places=None, ...):
    if first == second:
        # shortcut
        return
    ...
    if delta is not None:
    ...
    else:
        if places is None:
            places = 7

        if round(abs(second-first), places) == 0:
            return

    ...
    raise self.failureException(msg)

应该是:

if abs(round(second, places) - round(first, places)) == 0
    return

最佳答案

您提出的修复方案不会产生任何影响,您可以轻松证明:

>>> places = 2
>>> first, second = 69.88, 69.875
>>> round(abs(second-first), places)
0.0
>>> abs(round(second, places) - round(first, places))
0.0

这是浮点精度的问题,请参见例如Is floating point math broken? 69.88 无法准确表示:

>>> "{:.40f}".format(69.88)
'69.8799999999999954525264911353588104248047'

关于pythonunittest2assertAlmostEqual 与 `places` 工作不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28696783/

相关文章:

python - 如何在 Nose 下执行 "early return"导入?

python - Hadoop流式传输命令失败

python - 用 fabric 读取日志

python - 在列值和索引值上对 Pandas 数据框进行排序?

nose - 解决python中运行unittest的方式太多产生的困惑

python - 在一系列 Python 版本中支持 unittest2 功能的最 Pythonic 方式是什么?

python - 我无法让我的类(class)在 pygame 中工作

python - 根据正则表达式选择要调用的 Python 函数

python - 在 LSF 上运行 python 单元测试

python - 让一个测试方法返回多个测试结果