I want to be able to generate repeatable numbers using rand
in Clojure. (Specifically, I want results of calls to rand-nth
or Incanter\'s sample
Here's how you might define the function generator that you can seed that I described in the comments.
If you don't want doubles, see the Javadoc.
user=> (defn randfn
#_=> ([] (randfn (java.util.Random.)))
#_=> ([r] #(.nextDouble r)))
#'user/randfn
user=> (def source1 (randfn))
#'user/source1
user=> (source1)
0.6270662940925175
user=> (source1)
0.23351789802762046
Here's how you might create it with a seeded Random number generator.
user=> (def source2 (randfn (java.util.Random. 37)))
#'user/source2
user=> (take 3 (repeatedly #(source2)))
(0.7276532767062343 0.5136790759391296 0.7384220244718898)
user=> (def source3 (randfn (java.util.Random. 37)))
#'user/source3
user=> (take 3 (repeatedly #(source3)))
(0.7276532767062343 0.5136790759391296 0.7384220244718898
As a bonus, you could also use the newish ThreadLocalRandom or the not very new at all SecureRandom as your random number generators.
user=> (def secure-source (randfn (java.security.SecureRandom.)))
#'user/secure-source
user=> (take 3 (repeatedly #(secure-source)))
(0.9987555822097023 0.48452119609266475 0.443029180668418)