This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: unittest: assertAlmostEqual rounding error
Type: Stage: resolved
Components: Library (Lib) Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: mark.dickinson, sam-s
Priority: normal Keywords:

Created on 2017-05-30 17:26 by sam-s, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (3)
msg294772 - (view) Author: sds (sam-s) Date: 2017-05-30 17:26
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
```
msg294778 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2017-05-30 19:50
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.
msg294779 - (view) Author: sds (sam-s) Date: 2017-05-30 19:53
you are right, sorry.
History
Date User Action Args
2022-04-11 14:58:47adminsetgithub: 74700
2017-05-30 19:53:25sam-ssetstatus: open -> closed
resolution: not a bug
messages: + msg294779

stage: resolved
2017-05-30 19:50:04mark.dickinsonsetnosy: + mark.dickinson
messages: + msg294778
2017-05-30 17:26:28sam-screate