assert almost equal
次のような手段に頼らずにフロートの py.test を使用する方法:
assert x - 0.00001 <= y <= x + 0.00001
より具体的には、float のペアをアンパックせずにすばやく比較するための適切なソリューションを知っておくと役立ちます。
assert (1.32, 2.4) == i_return_tuple_of_two_floats()
assert almost equal
次のような手段に頼らずにフロートの py.test を使用する方法:
assert x - 0.00001 <= y <= x + 0.00001
より具体的には、float のペアをアンパックせずにすばやく比較するための適切なソリューションを知っておくと役立ちます。
assert (1.32, 2.4) == i_return_tuple_of_two_floats()
この質問はpy.testについて具体的に尋ねていることに気付きました。py.test 3.0 には、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
ドキュメントはこちらです。
あなたにとって「ほぼ」とは何かを指定する必要があります。
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())
これらの回答は長い間存在していますが、最も簡単で読みやすい方法は、テスト構造に使用せずに、多くの優れたアサーションに unittest を使用することだと思います。
(この回答に基づく)
import unittest
assertions = unittest.TestCase('__init__')
x = 0.00000001
assertions.assertAlmostEqual(x, 0) # pass
assertions.assertEqual(x, 0) # fail
# AssertionError: 1e-08 != 0
* を使用して戻り値をアンパックするだけで、新しい名前を導入する必要はありません。
i_return_tuple_of_two_floats = lambda: (1.32, 2.4)
assertions.assertAlmostEqual(*i_return_tuple_of_two_floats()) # fail
# AssertionError: 1.32 != 2.4 within 7 places
何かのようなもの
assert round(x-y, 5) == 0
それがunittestが行うことです
第二部について
assert all(round(x-y, 5) == 0 for x,y in zip((1.32, 2.4), i_return_tuple_of_two_floats()))
おそらくそれを関数でラップする方が良いでしょう
def tuples_of_floats_are_almost_equal(X, Y):
return all(round(x-y, 5) == 0 for x,y in zip(X, Y))
assert tuples_of_floats_are_almost_equal((1.32, 2.4), i_return_tuple_of_two_floats())
float だけでなく Decimals などでも機能するものが必要な場合は、python のmath.isclose()を使用できます。
# - rel_tol=0.01` is 1% difference tolerance.
assert math.isclose(actual_value, expected_value, rel_tol=0.01)
私はnose.toolsを使います。py.test ランナーとうまく連携し、他の同様に有用なアサート (assert_dict_equal()、assert_list_equal() など) があります。
from nose.tools import assert_almost_equals
assert_almost_equals(x, y, places=7) #default is 7