The assertAlmostEqual(x, y)
method in Python’s unit testing framework tests whether x and y are approximately equal. This is similar to self.assertEqual
but there are some additional things to be considered.
self.assertAlmostEqual(0.5, 0.4)
that won’t end it true, which is totally correct.
assertAlmostEqual
has an additional parameter place
which takes the no of decimal places upto which the number will be rounded of too. By default places=7
which makes the above two floats not equal.
self.assertAlmostEqual(0.12345999, 0.12345888, 5)
// 0.12345999 and 0.12345888 are equal when rounded to 5 places that is 0.12345 so they pass
For more precise calculations 4th parameter delta
can also be added which ensures difference between first and second must be less or equal to delta. Default value for delta
is 0.
self.assertAlmostEqual(0.12345999, 0.12345444, 5, 0.00001)
// Once rounded to 5 places the difference is 0.00001 so this will pass