pytest: assert almost equal

后端 未结 7 1507
时光说笑
时光说笑 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:38

    Something like

    assert round(x-y, 5) == 0
    

    That is what unittest does

    For the second part

    assert all(round(x-y, 5) == 0 for x,y in zip((1.32, 2.4), i_return_tuple_of_two_floats()))
    

    Probably better to wrap that in a function

    def tuples_of_floats_are_almost_equal(X, Y):
        return all(round(x-y, 5) == 0 for x,y in zip(X, Y))
    
    assert tuples_of_floats_are_almost_equal((1.32, 2.4), i_return_tuple_of_two_floats())
    

提交回复
热议问题