0
import org.scalacheck._
import org.scalacheck.Prop._

object Doubles extends Properties("Gen Doubles") {
  val positiveDouble = Arbitrary.arbitrary[Double] suchThat (_ > 0.0)
  val normalize = Arbitrary.arbitrary[Double] map (f => math.abs(f) / Double.MaxValue)
  def between(a: Double, b: Double) = normalize map (_ * (b - a) + a)
  property("normalize") = forAll(normalize) { f => 0.0 <= f && f <= 1.0 }
  property("between") = forAll(positiveDouble, positiveDouble) { (a: Double, b: Double) =>
    forAll(between(a, b)) { f =>
      a <= f && f <= b
    }
  }
}

Output via http://scastie.org/13056

+ Gen Doubles.normalize: OK, passed 100 tests.

! Gen Doubles.between: Falsified after 0 passed tests.
> ARG_0: 2.9635128477431505E249
> ARG_1: 1.807071439895287E-167

Where does my math fail?

EDIT solution:

val ascendingTuple = (for {
  a <- Arbitrary.arbitrary[Double]
  b <- Arbitrary.arbitrary[Double]
} yield(a, b))suchThat({case (a, b) => a < b})
Reactormonk
  • 20,410
  • 12
  • 66
  • 110

1 Answers1

1

The problem is that you are not enforcing that b should be greater than a, but your test assumes this. When the generated value for b is less than a, you get a number such that b <= f <= a, which fails your test. For a simple fix, try:

forAll(between(a, b)) { f =>
  if (a < b) {
    a <= f && f <= b
  } else {
    b <= f && f <= a
  }
}
Shadowlands
  • 14,544
  • 4
  • 40
  • 40