Assert two variables are almost equal in python

后端 未结 5 1951
爱一瞬间的悲伤
爱一瞬间的悲伤 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 13:48

    You can use the new isclose function introduced in Python 3.5

    PEP 485 adds the math.isclose() and cmath.isclose() functions which tell whether two values are approximately equal or “close” to each other. Whether or not two values are considered close is determined according to given absolute and relative tolerances. Relative tolerance is the maximum allowed difference between isclose arguments, relative to the larger absolute value

    import math
    a = 100.0
    b = 102.0
    c = 103.0
    
    assert math.isclose(a,b, rel_tol=0.02)
    assert math.isclose(a,c, rel_tol=0.02)
    

提交回复
热议问题