有没有在python中测试浮点近似相等的函数?就像是,
def approx_equal(a, b, tol):
return abs(a - b) < tol
Run Code Online (Sandbox Code Playgroud)
我的用例类似于Google的C++测试库gtest.h所定义的EXPECT_NEAR.
这是一个例子:
def bernoulli_fraction_to_angle(fraction):
return math.asin(sqrt(fraction))
def bernoulli_angle_to_fraction(angle):
return math.sin(angle) ** 2
def test_bernoulli_conversions():
assert(approx_equal(bernoulli_angle_to_fraction(pi / 4), 0.5, 1e-4))
assert(approx_equal(
bernoulli_fraction_to_angle(bernoulli_angle_to_fraction(0.1)),
0.1, 1e-4))
Run Code Online (Sandbox Code Playgroud)