Search code examples
javarandomclojure

How to implement a all inclusive random number function in Clojure?


I was wondering how to have inclusive random numbers in Clojure. I came up with this:

(import java.util.Random)

(def rnd 
  (Random.))
(defn random-float 
  [min max rnd] 
  (+ min (* (.nextDouble rnd) (- max min))))

It seems that Java only has inclusive/exclusive random functions. According the documentation:

The general contract of nextDouble is that one double value, chosen (approximately) uniformly from the range 0.0d (inclusive) to 1.0d (exclusive), is pseudorandomly generated and returned.

Is there a way to have an inclusive/inclusive version of this function. I was thinking about increasing the maximum value with a tiny bit (0.0000000000000001). Not sure what is the impact if I do so.

Would this work?

(random-float 0.0 1.0000000000000001 rnd)

Solution

  • How important is the double precision for your case?

    You could use integers for everything with clojure.core's rand-int e.g:

    • for a number between 0-100: (rand-int 101)
    • for a number between 0-1000: (rand-int 1001)
    • etc

    I'd also note that there are other Clojure rand-style functions such as random-sample and rand ; if rand-int isn't what you're looking for, still you probably won't need to fallback to Java.