Assert two variables are almost equal in python

后端 未结 5 1952
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-29 13:15

Here are two variables: earnings_forecast, actual_earning (numerical variables)

I want to assert if both these variables are equal with a diffe

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-29 14:03

    Simple approach:

    a, b = sorted(map(float, (a, b)))
    assert a + abs(a)*1.02 >= b
    

    You can use a custom Testcase subclass for use in tests:

    class FooTestCase(TestCase):
        def assertAlmostEqual(a, b):
            a, b = sorted(map(float, (a, b)))
            self.assertTrue(a + abs(a)*1.02 >= b)
    

提交回复
热议问题