As far as I know, exact comparison doesn't make much sense with floating point values as what is intended to be 0.0001 can actually be something like 0.0001000...0001... Should I implement my own comparison function to specify precision or is there a common practice for this?
I used to use the following with C# (which, I suspect, is still wrong as a Double value can be probably uncapable of representing 0.0001 at all, even set as a constant (as Michael Borgwardt explained here)):
public static bool AlmostEquals(this double x, double y, double precision = 0.0001)
{
if (precision < 0.0)
throw new ArgumentException();
return Math.Abs(x - y) <= precision;
}
Should I do something alike in Scala?
Yes, you can do the same thing as in Java. You could also use some of Scala's cool features and pimp the Double class with a ~= method that takes an implicit precision parameter that only needs to be specified once.
scala> case class Precision(val p:Double)
defined class Precision
scala> class withAlmostEquals(d:Double) {
def ~=(d2:Double)(implicit p:Precision) = (d-d2).abs <= p.p
}
defined class withAlmostEquals
scala> implicit def add_~=(d:Double) = new withAlmostEquals(d)
add_$tilde$eq: (d: Double)withAlmostEquals
scala> 0.0~=0.0
<console>:12: error: could not find implicit value for parameter p: Precision
0.0~=0.0
^
scala> implicit val precision = Precision(0.001)
precision: Precision = Precision(0.001)
scala> 0.0 ~= 0.00001
res1: Boolean = true
Or with 2.10...
case class Precision(p:Double)
implicit class DoubleWithAlmostEquals(val d:Double) extends AnyVal {
def ~=(d2:Double)(implicit p:Precision) = (d - d2).abs < p.p
}
Use Tolerance from scalautils
import org.scalautils._
import TripleEquals._
import Tolerance._
val result = 2.000001
result: Double = 2.000001
result === 2.0 +- .001
res0: Boolean = true
result === 2.0 +- .000000001
res1: Boolean = false
Update: For Scala 2.11
import org.scalatest._
import org.scalatest.Matchers._
val r = 4
val rr = (r === 2 +- 1)
r: Int = 4
rr: Boolean = false