Thanks roippi
for the great idea, I modified your code somewhat:
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
I changed a few things
1) I check the exponent as well as the significand (That's a top drawer word isn't it)
2) I convert the significand and exponent to float / int respectively. This may not be necessary but i am more comfortable checking the equality of numbers as numbers rather than strings.
3) Jim Lewis
noted that i need to adjust my tolerance by one since the proper format string {0:.3e} of 0.0123 is 1.230E-2 not 0.123E-1. i.e. if you want three significant figures you only want two digits after the decimal as the digit before the decimal is also significant.
Hers is an example of implementation
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
And the output:
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)
Thank you both for your feedback.