pytest: assert almost equal

后端 未结 7 1504
时光说笑
时光说笑 2020-12-24 03:55

How to do assert almost equal with py.test for floats without resorting to something like:

assert x - 0.00001 <= y <= x + 0.00001
<         


        
7条回答
  •  抹茶落季
    2020-12-24 04:42

    If you want something that works not only with floats but for example Decimals you can use python's math.isclose:

        # - rel_tol=0.01` is 1% difference tolerance.
        assert math.isclose(actual_value, expected_value, rel_tol=0.01)
    

    Docs - https://docs.python.org/3/library/math.html#math.isclose

提交回复
热议问题