Skip to content

Instantly share code, notes, and snippets.

@gigamonkey
Created November 15, 2013 18:19
Show Gist options
  • Save gigamonkey/7489116 to your computer and use it in GitHub Desktop.
Save gigamonkey/7489116 to your computer and use it in GitHub Desktop.
Random doubles in range
import scala.annotation.tailrec
import scala.util.Random
/*
* Pick a random number between to double values, inclusive.
*/
@tailrec def between(low: Double, high: Double, r: Random): Double = {
if (low == high) {
low
} else {
val mid = low + (high/2 - low/2)
if (r.nextBoolean) between(low, mid, r) else between(mid, high, r)
}
}
@jcoveney
Copy link

Nice! One thing I've been thinking about, given that we have the Generator, do you think we should use them wherever possible? Like we can choose one fundamental Generator that uses Random, and then everything else can use that? In this case you could use Generator[Boolean] and create the Between generator for double, and so on.

Obviously this could be seen as a helper around the random generator, but the benefit of composing generators is that then we control the class where the Random class (and thus the seed) is truly set, because we force people to compose generators otherwise. Just a thought.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment