聊聊gost的DeltaCompare

本文主要研究一下gost的DeltaComparegit

DeltaCompare

gost/math/compare.gogithub

// equivalent to math.Abs(expected - actual) <= delta
func DeltaCompareFloat64(expected float64, actual float64, delta float64) bool {
    if expected > actual {
        return expected-actual <= delta
    }
    return actual-expected <= delta
}

func DeltaCompareFloat32(expected float32, actual float32, delta float32) bool {
    if expected > actual {
        return expected-actual <= delta
    }
    return actual-expected <= delta
}
DeltaCompareFloat64及DeltaCompareFloat32對比兩個float類型的差值是否小於等於指定的delta

實例

gost/math/compare_test.goui

func TestFloat64(t *testing.T) {
    assert.True(t, DeltaCompareFloat64(12.3334, 12.3344, 0.01))
    assert.True(t, DeltaCompareFloat64(12.3334, 12.32981, 0.01))
    assert.False(t, DeltaCompareFloat64(12.3334, 12.0325, 0.01))
}

func TestCompareFloat32(t *testing.T) {
    assert.True(t, DeltaCompareFloat32(12.3334, 12.3344, 0.01))
    assert.True(t, DeltaCompareFloat32(12.3334, 12.32981, 0.01))
    assert.False(t, DeltaCompareFloat64(12.3334, 12.0325, 0.01))
}

小結

gost的提供了DeltaCompareFloat3二、DeltaCompareFloat64方法用於對比兩個float類型的差值是否小於等於指定的delta。code

doc

相關文章
相關標籤/搜索