Issue 30515: unittest: assertAlmostEqual rounding error (original) (raw)

I get this unittest failure:

Traceback (most recent call last):
  File "zzz.py", line 348, in test_opposite
    self.assertAlmostEqual(a, b, places=2)
AssertionError: 1.1036640046288428 != 1.0986122886681098 within 2 places

This seems incorrect: 1.1036640046288428 rounded off to 2 places is 1.10 and so is 1.0986122886681098.

E.g., in Lisp:

> (round 1.1036640046288428d0 0.01)
110 ;
0.0036640292157588336d0
> (round 1.0986122886681098d0 0.01)
110 ;
-0.001387686744974238d0

The assertAlmostEqual comparison looks at the difference between the two values, and rounds that to 2 decimal places. In this case, the difference is approximately 0.00505, which rounded to 2 decimal places is 0.01.

If instead each of the two values were rounded and the rounded values compared, you'd end up in a situation where (for example) self.assertEqual(1.144999999, 1.145000001, places=2) failed, despite the values being only 2 billionths apart.