ScalaTest - testing equality between two floating point arrays with error margin

杀马特。学长 韩版系。学妹 提交于 2019-12-08 16:37:38

问题


Let's say I have a function that returns a array of doubles. I want to test this function and have calculated the correct value by hand. However since it's floating point numbers, I can't do direct comparisons so is there any sweet syntax by ScalaTest that makes me able to compare double arrays with an epsilion/error margin?

Thanks


回答1:


Well as I feared there is no nice syntax in ScalaTest for this, and I will accept my own answer with a very basic solution.

val Eps = 1e-3 // Our epsilon

val res = testObject.test // Result you want to test.
val expected = Array(...) // Expected returning value.

res.size should be (expected.size)

for (i <- 0 until res.size) res(i) should be (expected(i) +- Eps)

As seen, this works. Then you can make it nicer by perhaps defining an implicit method.




回答2:


How about:

 import Inspectors._
 import scala.math._

 forExactly(max(a1.size, a2.size), a1.zip(a2)){case (x, y) => x shouldBe (y +- eps)}

Or you can provide custom equality (there is a built-in one as @Suma sugested):

  import org.scalactic._

  implicit val custom = TolerantNumerics.tolerantDoubleEquality(eps)

  a1 shouldBe (a2)


来源:https://stackoverflow.com/questions/27213930/scalatest-testing-equality-between-two-floating-point-arrays-with-error-margin

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