相关疑难解决方法(0)

测试浮点相等

有没有在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)

python floating-point comparison

36
推荐指数
4
解决办法
3万
查看次数

标签 统计

comparison ×1

floating-point ×1

python ×1