Python 的单元测试框架中的 Assert几乎相等(x,y)方法测试 x
和 y
是否大致相等,假设它们是浮点数。
assertAlmostEqual()
的问题在于它只能在浮动上工作。我正在寻找一个像 assertAlmostEqual()
这样的方法,它可以处理浮点数列表、浮点数集合、浮点数字典、浮点数元组、浮点数元组列表、浮点数集合等等。
例如,让 x = 0.1234567890
,y = 0.1234567891
。x
和 y
几乎相等,因为除了最后一个数字之外,它们在每个数字上都是一致的。因此,self.assertAlmostEqual(x, y)
是 True
,因为 assertAlmostEqual()
适用于浮点数。
我正在寻找一个更通用的 assertAlmostEquals()
,它也评估以下对 True
的调用:
self.assertAlmostEqual_generic([x, x, x], [y, y, y])
.self.assertAlmostEqual_generic({1: x, 2: x, 3: x}, {1: y, 2: y, 3: y})
.self.assertAlmostEqual_generic([(x,x)], [(y,y)])
.是否有这样的方法,还是我必须自己实现它?
澄清:
assertAlmostEquals()
有一个名为 places
的可选参数,通过计算整数为十进制 places
的差值来比较这些数字。默认情况下 places=7
,因此 self.assertAlmostEqual(0.5, 0.4)
为 False,而 self.assertAlmostEqual(0.12345678, 0.12345679)
为 True。我的推测性 assertAlmostEqual_generic()
应该具有相同的功能。
如果两个列表的数目几乎相等,且顺序完全相同,则认为它们几乎相等。
类似地,如果可以将两个集合转换为几乎相等的列表(通过为每个集合分配顺序) ,则认为它们几乎相等。
类似地,如果每个字典的键集几乎等于另一个字典的键集,并且对于每个这样的几乎相等的键对,有一个相应的几乎相等的值,则两个字典被认为是几乎相等的。
一般来说: 如果两个集合相等,我认为它们几乎相等,除了一些对应的浮点数几乎相等。换句话说,我希望真正地比较对象,但是在比较沿途的浮点数时具有较低的(定制的)精度。