F#Assert.AreEquals失败,带有两个文字 [英] F# Assert.AreEquals fails with two literals

查看:94
本文介绍了F#Assert.AreEquals失败,带有两个文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下单元测试:

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)

当我运行单元测试时,它失败了,但是'expected'和'actual'的值相等:

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

expected和Actual分别被推定为float和double,但我的印象是float只是double的简写. 有什么解释吗?

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?

编辑 根据@Gustavo的评论,我将最后一行更改为:

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

Assert.AreEqual(expected, actual, 0.000000000000001)

测试通过.

推荐答案

浮点值的相等很棘手,因为小的舍入差异就足以导致不等式.

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)

这篇关于F#Assert.AreEquals失败,带有两个文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆