vendredi 4 janvier 2019

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)




Aucun commentaire:

Enregistrer un commentaire