Reputation: 8572
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)
Upvotes: 0
Views: 497
Reputation: 2836
How important is the double precision for your case?
You could use integers for everything with clojure.core's rand-int
e.g:
(rand-int 101)
(rand-int 1001)
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.
Upvotes: 1