Python 2.7 使用 assertAlmostEqual 的单元测试无法正常运行

Python 2.7 unittest using assertAlmostEqual is not functioning properly

我的 python 版本是 2.7.13。

我需要使用 unittest 模块进行测试,我正在测试的数据类型是浮点数。在文档中,它说在比较浮点数是否相等时使用 assertAlmostEqual 作为小差异。

这是我做的:

self.assertAlmostEqual(41.7777777777776, 41.777, places=3)

我运行上面的代码,它产生了一个失败的测试结果,如下所示:

self.assertAlmostEqual(41.7777777777776, 41.777, places=3) AssertionError: 41.7777777777776 != 41.777 within 3 places

我做错了什么,或者这是一个错误?

来自the docs

Test that first and second are approximately (or not approximately) equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero. Note that these methods round the values to the given number of decimal places (i.e. like the round() function) and not significant digits.

在你的情况下,round(41.7777777777776 - 41.777, 3) != 0.0

您的数字不等于小数点后三位,as defined by assertAlmostEqual:

Test that first and second are approximately (or not approximately) equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero.

四舍五入到小数点后 3 位的数字之差为 0.001