断言在Python中两个变量几乎相等

2022-05-17 00:00:00 python python-unittest

问题描述

这里有两个变量:earnings_forecastactual_earning(数值变量)

我要断言这两个变量是否相等,actual_earning变量的差值为±2%。

假设: earnings_forecast = 6 actual_earnings = 5.19

我不能使用assertEqual(earnings_forecast, actual_earnings),因为它将尝试执行完全匹配,相反,我想断言这两个变量几乎相等,可以接受±2%的差异。


解决方案

您可以使用在Python3.5中引入的新isClose函数

PEP 485添加了math.islose()和cmath.islose()函数, 判断两个值是否大致相等或接近 其他的。确定是否认为两个值接近 根据给定的绝对公差和相对公差。相对的 容差是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)

相关文章