224

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()
4

8 に答える 8

368

この質問は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

ドキュメントはこちらです。

于 2016-09-21T18:05:33.563 に答える
49

あなたにとって「ほぼ」とは何かを指定する必要があります。

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())
于 2011-12-19T10:44:50.780 に答える
17

これらの回答は長い間存在していますが、最も簡単で読みやすい方法は、テスト構造に使用せずに、多くの優れたアサーションに unittest を使用することだと思います。

アサーションを取得し、unittest.TestCase の残りを無視します

(この回答に基づく)

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
于 2016-06-08T14:45:33.457 に答える
12

何かのようなもの

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())
于 2011-12-19T10:45:55.453 に答える
11

float だけでなく Decimals などでも機能するものが必要な場合は、python のmath.isclose()を使用できます。

# - rel_tol=0.01` is 1% difference tolerance.
assert math.isclose(actual_value, expected_value, rel_tol=0.01)
于 2019-02-07T15:21:23.093 に答える
4

私は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 
于 2016-06-15T22:00:23.793 に答える