F# Assert.AreEquals fails with two literals

笑着哭i 提交于 2019-12-11 03:08:22

问题


I have the following unit test:

open System
open System.Collections.Generic
open Microsoft.VisualStudio.TestTools.UnitTesting

[<TestClass>]
type Test_Spectra () =

    let standard = new Standard1()

    [<TestMethod>]
    member x.LightTransmittance () =

        let input = Test_Spectra.TestSprectra1
        let expected = 0.32728222797751
        let actual = standard.LightTransmittance(input)

        Assert.AreEqual(expected, actual)

When I run the unit test it fails, however the values for 'expected' and 'actual' are equal:

Expected and Actual are inferred as a float and double respectively, but I was under the impression that float is simply shorthand for double. Is there any explanation for this?

EDIT As per @Gustavo's comment, I have changed the final line to:

Assert.AreEqual(expected, actual, 0.000000000000001)

and the test passes.


回答1:


Equality for floating point values is tricky since a small rounding difference will be enough to result in an inequality.

Using equality for comparing two floats in your code is generally a bad idea when at least one of those numbers come from calculations. The same applies for unit tests.

What you usually do is define what is your tolerance and use comparison, instead of equality.

    let input = Test_Spectra.TestSprectra1
    let expected = 0.32728222797751
    let actual = standard.LightTransmittance(input)

    let tolerance = 0.000000000000001

    Assert.AreEqual(expected, actual, tolerance)



回答2:


For F#, the advantages of unquote are hard to ignore.

For example, if you wanted to write something similar to @Gustavo's answer you'd use stuff like:

// In helpers somewhere or I'm sure some lib has relevant functions
let inline equalsWithinTolerance x tol y = abs(x-y) < tol

test <@ expected |> equalsWithinTolerance .000001 actual @>

let inline (~=) x = equalsWithinTolerance x .00000001
test <@ expected ~= actual @>


来源:https://stackoverflow.com/questions/26142410/f-assert-areequals-fails-with-two-literals

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!