ScalaTest比较浮点数和公差-断言失败

时间:2019-05-29 14:54:45

标签: floating-point assert scalatest

我正在使用ScalaTest(3.0.4),无法获得将浮点数与公差进行比较的任何示例。这是我所拥有的:

import org.scalatest.{MustMatchers, WordSpec}

class DetectionClusteringSpec extends WordSpec with MustMatchers {

    "EmbeddingsGroup.vecdist" should {
        "correctly compute vector distance" in {
            val dist = EmbeddingsGroup.vecdist(TestDetections.emb1,TestDetections.emb4)
            // Note: The above method returns a Float. 

            dist mustBe 3.058 +- 0.1
        }
    }

以上编译,但是当我运行测试时,出现以下失败:

3.0579379 was not equal to 3.058 +- 0.1
Expected :3.058 +- 0.1
Actual   :3.0579379

我还绑定了以下断言:

assert(dist === 3.058)

但是,这也不起作用,并且会出现以下故障:

3.0579379 did not equal 3.058
Expected :3.058
Actual   :3.0579379

我已经阅读了许多将浮点数与上述两种语法进行比较的示例,看来它们应该可以工作。我的第一个示例直接来自the documentation

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

由于distFloat,而其他参数是Double,请尝试像这样将dist转换为Double

dist.toDouble mustBe 3.058 +- 0.1

或使其他参数像这样浮动

dist mustBe 3.058f +- 0.1f
相关问题