Ava*_*nti -2 python python-unittest
这里有两个变量:earnings_forecast,actual_earning(数值变量)
我想断言这两个变量是否相等,相对于actual_earning变量可接受±2%的差异.
假设:
earnings_forecast = 6
actual_earnings = 5.19
我不能使用,assertEqual(earnings_forecast, actual_earnings)因为它会尝试做一个完全匹配,而我想断言这两个变量几乎相等,可接受的±2%差异.
Jul*_*l3k 14
您可以使用Python 3.5中引入的新isclose函数
PEP 485添加了math.isclose()和cmath.isclose()函数,它们判断两个值是否大致相等或相互"接近".根据给定的绝对和相对容差确定两个值是否被认为是接近的.相对容差是isclose参数之间允许的最大差异,相对于较大的绝对值
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3525 次 |
| 最近记录: |