2

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:

lightTransmittanceFails

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.

Nick
  • 685
  • 12
  • 27

2 Answers2

6

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)
Gus
  • 25,839
  • 2
  • 51
  • 76
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 @>
Community
  • 1
  • 1
Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249