Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 912
Johan S Avatar asked Nov 30 '14 13:11

Johan S


2 Answers

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.

like image 158
Johan S Avatar answered Nov 16 '22 00:11

Johan S


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)

like image 38
dk14 Avatar answered Nov 16 '22 02:11

dk14