Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScalaTest - check for "almost equal" for floats and objects containing floats [duplicate]

While writing tests for operations with floats or objects containing floats (like vectors or matrices), I often want to test not for equality, but for "almost equal" (difference allowed to be some epsilon).

When using ScalaTest FunSuite, one normally writes assert(xxx == yyy). With floats and likes I can write assert(math.abs(xxx - yyy)<epsilon), but then I do not get the nice feature of the ScalaTest assert macro of being reported the compared values as a part of the failure message.

How can I perform testing of float "almost equality" in ScalaTest, so that when the test fails, the values are written as a part of the failure message?

Test example:

import org.scalatest.FunSuite

class FloatTest extends FunSuite {
  test("Testing computations") {
    import math._
    assert(sin(Pi/4)==sqrt(0.5))
    assert(sin(Pi)==0)
  }
}
like image 804
Suma Avatar asked Apr 29 '15 08:04

Suma


1 Answers

It can be done using TolerantNumerics and using === instead of ==.

import org.scalactic.TolerantNumerics
import org.scalatest.FunSuite

class FloatTest extends FunSuite {

  val epsilon = 1e-4f

  implicit val doubleEq = TolerantNumerics.tolerantDoubleEquality(epsilon)

  test("Testing computations") {
    import math._
    assert(sin(Pi / 4) === sqrt(0.5))
    assert(sin(Pi) === 0.0)
  }
}

For your own types you can define your own subclasses of Equality[T].

like image 62
Suma Avatar answered Oct 08 '22 02:10

Suma