我希望能够使用生成可重复的数字rand
在 Clojure 中。 (具体来说,我想要调用的结果rand-nth
或Incanter的sample
可重复,这些称为rand-int
这又调用rand
).
我想通了这个问题 https://stackoverflow.com/questions/22441860/why-doesnt-repeatedly-generate-reproducible-random-numbers-when-using-a-seed-in如果我使用 clojure.data.generators,我可以重置随机状态:
(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.generators 中的函数,这并不奇怪:
(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
我怎样才能恢复随机状态以获得可重复的结果rand
?到目前为止我还没有找到任何关于此的文档。
(另一个问题 https://stackoverflow.com/questions/22429778/re-bind-a-random-number-generator-in-clojure听起来好像可能是同一个问题,但它询问的是完全不同的事情。)
可能不是最干净的方法,但你可以通过重新定义使其工作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 8 8) 。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)