Need to test almost equal within tests, but without absolute epsilon


#1

I see there is a way in ScalaCheck to test for almost equal relative to an absolute epsilon, however, what would be perhaps more useful would be an epsilon which is interpreted as a fraction of the value being checked.

This was briefly discussed here but I’m not sure if it was implemented.

I can implement this myself, but I’m not sure what the most general form should be.

  def almostEqual(tolerance:Double)(x:Double, y:Double):Boolean = {
    ( x == y) ||  abs(x - y ) < tolerance * max(abs(x),abs(y))
  }

The semantics is that almostEqual(0.3)(x,y) is that the distance from x to y is within 30% of the maximum (in absolute value) of x and y.


#2

I don’t know if ScalaCheck has that concept, but ScalaTest certainly does. The trick is that you can’t do this with ==, you have to use a different equality operator, either the should be syntax or Scalactic’s === operator.

(NB: Scalactic is a lower-level library that ScalaTest is built on – it defines a raft of more-specific numeric types, and a few handy tools such as ===. ScalaTest transitively includes Scalactic, so you have that available to you.)

See the discussion of equality checking in ScalaTest, and especially the Scalactic docs – looks for the Equality trait in there, which discusses this exact use case.

I’ll warn that this is the camel’s nose in the tent for typeclasses – I don’t recall whether you’ve gotten to them yet or not, but this is a good example of why they are so helpful…