如何使用rand-int生成可重复的随机序列 [英] How to generate repeatable random sequences with rand-int
问题描述
我希望能够使用Clojure中的 rand
生成可重复的数字。 (具体来说,我希望调用 rand-nth
或Incanter的 sample
的结果可重复,而这些调用 rand-int
依次称为 rand
)。
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
to be repeatable, and these call rand-int
which in turn calls rand
).
I从这个问题中找出来如果我使用clojure.data.generators,则可以重置随机状态:
I figured out from this question that if I use clojure.data.generators, I can reset the random state:
(require '[clojure.data.generators :as gen])
(alter-var-root #'gen/*rnd* (constantly (java.util.Random. 437)))
(gen/reservoir-sample 5 (range 1000)) ; => [940 591 636 12 755]
(gen/reservoir-sample 5 (range 1000)) ; => [376 540 827 307 463]
; reset random state:
(alter-var-root #'gen/*rnd* (constantly (java.util.Random. 437)))
; now the same results are generated again:
(gen/reservoir-sample 5 (range 1000)) ; => [940 591 636 12 755]
(gen/reservoir-sample 5 (range 1000)) ; => [376 540 827 307 463]
但是,该方法似乎只影响clojure.data中的函数。生成器,这并不奇怪:
However, that method only seems to affect functions in clojure.data.generators, which isn't surprising:
(alter-var-root #'gen/*rnd* (constantly (java.util.Random. 437)))
(rand) ; => 0.9372552374760151
(rand) ; => 0.2712729314667742
; reset random state:
(alter-var-root #'gen/*rnd* (constantly (java.util.Random. 437)))
; not same results as before:
(rand) ; => 0.630238593767316
(rand) ; => 0.426744420572015
如何恢复随机状态,例如从<$ c中获得可重复的结果$ c> rand ?到目前为止,我还没有找到任何相关文档。
How can I restore the random state in such as way as to get repeatable results from rand
? So far I haven't found any documentation about this.
(另一个问题听起来好像是同一问题,但它询问的是完全不同的东西。)
(Another question sounds as if it might be the same issue, but it's asking about something completely different.)
推荐答案
可能不是最干净的方法,但您可以通过重新定义 clojure.core / rand
:
Probably not the cleanest way, but you can make it work by redefining clojure.core/rand
:
(ns clojure.core)
(def r (java.util.Random. 1))
(defn rand
([] (.nextDouble r))
([n] (.nextInt r n)))
(take 10 (repeatedly #(rand-int 10)))
每次运行它都会产生(5 8 7 3 4 4 4 6 6 8 8)。
This produces (5 8 7 3 4 4 4 6 8 8) every time I run it.
这篇关于如何使用rand-int生成可重复的随机序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!