How to compare floating-point values safely in Scala

1 Answer

0 votes
/*
 * ==========================================================
 * Title: Safe Floating-Point Comparison in Scala
 * ==========================================================
 *
 * Floating-point numbers should not be compared directly
 * with == because rounding errors can occur during
 * mathematical operations.
 *
 * Recommended approach:
 * Compare values using a small tolerance (epsilon).
 */

/**
 * Utility methods for floating-point comparisons.
 */
object NumberUtils {

  // Default tolerance for Double comparisons
  private val DefaultEpsilon: Double = 1e-9

  /**
   * Returns true when two Double values are
   * sufficiently close to be considered equal.
   */
  def approximatelyEqual(
      a: Double,
      b: Double,
      epsilon: Double = DefaultEpsilon
  ): Boolean =
    math.abs(a - b) <= epsilon
}

/**
 * Application entry point.
 *
 * Using @main is the recommended approach in Scala 3
 * and avoids deprecation warnings associated with App.
 */
@main
def floatingPointComparisonDemo(): Unit = {

  val expected = 0.3
  val actual = 0.1 + 0.2

  println(s"Expected value: $expected")
  println(s"Actual value:   $actual")

  // Direct comparison is unreliable
  println(s"Using == : ${expected == actual}")

  // Safe comparison using tolerance
  println(
    s"Using approximatelyEqual : ${
      NumberUtils.approximatelyEqual(expected, actual)
    }"
  )
}


                
/*
run:

Expected value: 0.3
Actual value:   0.30000000000000004
Using == : false
Using approximatelyEqual : true

*/




 



answered Oct 7 by avibootz
...