2024-03-28 12:51:24 发布
网友
如何使用py.test对float执行assert almost equal操作,而不使用类似于:
assert almost equal
assert x - 0.00001 <= y <= x + 0.00001
更具体地说,了解一个简洁的解决方案,以便快速比较成对的浮点,而不必拆开它们:
assert (1.32, 2.4) == i_return_tuple_of_two_floats()
如果您有权访问NumPy,它就有很好的浮点比较功能,可以与^{}进行成对比较。
然后你可以做如下事情:
numpy.testing.assert_allclose(i_return_tuple_of_two_floats(), (1.32, 2.4))
您必须指定“几乎”是什么:
assert abs(x-y) < 0.0001
要应用于元组(或任何序列):
def almost_equal(x,y,threshold=0.0001): return abs(x-y) < threshold assert all(map(almost_equal, zip((1.32, 2.4), i_return_tuple_of_two_floats())
我注意到这个问题是关于py.test的。test 3.0包含一个approx()函数(好吧,真的是一个类),对于这个目的非常有用。
approx()
import pytest assert 2.2 == pytest.approx(2.3) # fails, default is ± 2.3e-06 assert 2.2 == pytest.approx(2.3, 0.1) # passes # also works the other way, in case you were worried: assert pytest.approx(2.3, 0.1) == 2.2 # passes
文档在这里:https://docs.pytest.org/en/latest/reference.html#pytest-approx
如果您有权访问NumPy,它就有很好的浮点比较功能,可以与^{} 进行成对比较。
然后你可以做如下事情:
您必须指定“几乎”是什么:
要应用于元组(或任何序列):
我注意到这个问题是关于py.test的。test 3.0包含一个
approx()
函数(好吧,真的是一个类),对于这个目的非常有用。文档在这里:https://docs.pytest.org/en/latest/reference.html#pytest-approx
相关问题 更多 >
编程相关推荐