TestXS.clj (require 'XorShift) (let [ r_def (XorSh […]
TestXS.clj (require 'XorShift) (let [ r_def (XorSh […]
TestXS.clj (require 'XorShift) (let [ r_def (XorShift/make-XorShift-defaultSeed) r_const (XorShift/make-XorShift 100) r (XorShift/make-XorShift) a (atom nil) ] ;デフォルトのシード値を取得 (println ">> defaults") (println XorShift/defaults) ;今の乱数に与えたシード値初期値 (println ">> seeds in r") (println (:seeds r)) ;乱数の生データを取得 (println ">> rand 0 to UInt32Max") (loop[i 0](when(< i 5) (println (XorShift/-rand r_def)) (recur(inc i)))) ;0-100の乱数(100含む)を整数で取得 (println ">> randInt 0 to 100") (loop[i 0](when(< i 5) (println (XorShift/randInt r_const 0 100)) (recur(inc i)))) ;0-1の乱数を浮遊小数点で取得 (println ">> randFloat 0 to 1") (loop[i 0](when(< i 5) (println (XorShift/randFloat r 0 1)) (recur(inc i)))) ;listのシャッフル ;値渡しとなるので元の配列は破壊されない (println ">> shuffle list") (reset! a (for[i (range 20)] i)) (println (XorShift/-shuffle r @a)) (println @a) ;今の乱数を回した回数 (println ">> randCount in r") (println @(:randCount r)) ) ;XorShift.clj (ns XorShift) (def defaults{ :x 123456789 :y 362436069 :z 521288629 :w 88675123 }) (defprotocol IXorShift (-rand[self]) (randInt[self & [min max]]) (randFloat[self & [min max]]) (-shuffle[self _arr]) ) (def MXorShift{ :-rand(fn[self] (swap! (:randCount self) inc) (let [t (bit-xor @(:x self) (bit-and (bit-shift-left @(:x self) 11) 0xFFFFFFFF))] (reset! (:x self) @(:y self)) (reset! (:y self) @(:z self)) (reset! (:z self) @(:w self)) (reset! (:w self) (bit-xor (bit-xor @(:w self) (bit-shift-right @(:w self) 19)) (bit-xor t (bit-shift-right t 8)))) ) ) :randInt(fn[self & {:keys [min max] :or {min 0,max 0x7FFFFFFF}}] (+(mod(-rand self) (inc(- max min))) min) ) :randFloat(fn[self & {:keys [min max] :or {min 0,max 1}}] (+(*(float(/(mod(-rand self) 0xFFFF) 0xFFFF)) (- max min)) min) ) :-shuffle(fn[self _arr] (let [arr (map #(atom %1) _arr)] (loop[i 0](when(< i (dec(count arr))) ; (let [r (randInt self i (dec(count arr)))] ; (let [tmp @(nth arr i)] ; (reset! (nth arr i) @(nth arr r)) ; (reset! (nth arr r) tmp) ; )) (recur(inc i)))) (map (fn[v]@v) arr) ) ) }) (defrecord XorShift[w x y z seeds randCount]) (extend XorShift IXorShift MXorShift) (defn make-XorShift ([](make-XorShift 10)) ([{:keys [w x y z] :or {w 10,x nil,y nil,z nil}}] (let [x (if(= nil x) (bit-shift-left w 13) x)] (let [y (if(= nil y) (bit-xor (bit-shift-right w 9) (bit-shift-left x 6)) y)] (let [z (if(= nil z) (bit-shift-right y 7) z)] (let [seeds { :x x :y y :z z :w w }] (XorShift. (atom w) (atom x) (atom y) (atom z) seeds (atom 0)) )))) ) ) (defrecord XorShift-defaultSeed[w x y z seeds randCount]) (extend XorShift-defaultSeed IXorShift MXorShift) (defn make-XorShift-defaultSeed[] (let [w (:w defaults),x (:x defaults),y (:y defaults),z (:z defaults)] (let [seeds { :x x :y y :z z :w w }] (XorShift-defaultSeed. (atom w) (atom x) (atom y) (atom z) seeds (atom 0)) )) )