感谢roippi 的好主意,我稍微修改了您的代码:
def assertAlmostEqualSigFig(self, arg1,arg2,tolerance=2):
if tolerance > 1:
tolerance -= 1
#end
str_formatter = '{0:.' + str(tolerance) + 'e}'
significand_1 = float(str_formatter.format(arg1).split('e')[0])
significand_2 = float(str_formatter.format(arg2).split('e')[0])
exponent_1 = int(str_formatter.format(arg1).split('e')[1])
exponent_2 = int(str_formatter.format(arg2).split('e')[1])
self.assertEqual(significand_1, significand_2)
self.assertEqual(exponent_1, exponent_2)
return
我改变了一些东西
1) 我检查指数和有效数字(不是最上面的抽屉词)
2) 我将有效数和指数分别转换为 float / int。这可能不是必需的,但我更愿意将数字的相等性检查为数字而不是字符串。
3) Jim Lewis 注意到我需要将容差调整一,因为 0.0123 的正确格式字符串 {0:.3e} 是 1.230E-2 而不是 0.123E-1。也就是说,如果你想要三个有效数字,你只需要小数点后的两位数,因为小数点前的数字也很重要。
她是一个实现的例子
class testSigFigs(Parent_test_class):
@unittest.expectedFailure
def test_unequal_same_exp(self):
self.assertAlmostEqualSigFig(0.123, 0.321, 3)
@unittest.expectedFailure
def test_unequal_diff_exp(self):
self.assertAlmostEqualSigFig(0.123, 0.0321, 3)
@unittest.expectedFailure
def test_equal_diff_exp(self):
self.assertAlmostEqualSigFig(0.0123, 0.123, 3)
def test_equal_same_exp(self):
self.assertAlmostEqualSigFig(0.123, 0.123, 3)
def test_equal_within_tolerance(self):
self.assertAlmostEqualSigFig(0.123, 0.124, 2)
#end
还有输出:
test_equal_diff_exp (__main__.testSigFigs) ... expected failure
test_equal_same_exp (__main__.testSigFigs) ... ok
test_equal_within_tolerance (__main__.testSigFigs) ... ok
test_unequal_diff_exp (__main__.testSigFigs) ... expected failure
test_unequal_same_exp (__main__.testSigFigs) ... expected failure
----------------------------------------------------------------------
Ran 5 tests in 0.081s
OK (expected failures=3)
感谢两位的反馈。