ScalaTest - testing equality between two floating

2019-06-16 16:10发布

问题:

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)