如何使用rand-int生成可重复的随机序列 [英] How to generated repeatable random sequences with rand-int

查看:158
本文介绍了如何使用rand-int生成可重复的随机序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Clojure中使用 rand 生成可重复的数字。 (具体来说,我想要调用 rand-nth 或Incanter的示例的结果是可重复的,这些调用 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).

这个问题找出了如果我使用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

如何恢复随机状态以获得可重复的结果 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 8 8)。

This produces (5 8 7 3 4 4 4 6 8 8) every time I run it.

这篇关于如何使用rand-int生成可重复的随机序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆