[Openmcl-devel] RANDOM SEED

Janusz Podrazik info at mracpublishing.com
Sun Jun 12 14:36:46 UTC 2011


The question is: how to return the same sequence of numbers
using random system. The idea was not to build new one but
find a way in which - if need it - personal 'seed-state' can
be saved and used.

The solution I found is simple, and with out compromising
the random system with other alternatives - I think.
If any of you found/have other solution to the problem
and like to share the code, please let me know.

best wishes, 

Janusz

(defun save-random-state (file &optional (state *random-state*)) 
(with-open-file (o file :direction :output
 :if-does-not-exist :create
 :if-exists :supersede)
(with-standard-io-syntax
(format o "~&;;; dumped ~D~%~S~%" (get-universal-time) state)
(values state file))))

(defun load-random-state (file)
(if (probe-file file)
(with-open-file (i file :direction :input)
(with-standard-io-syntax
(values (read i) file))) nil))

;(save-random-state "~/lisp/seed-state")
;(load-random-state "~/lisp/seed-state")

;if 'seed-state' file is not found 'default' random-state is used.

(defun seed-state (n)
;(seed-state 0.34) => 0.7094518
;(seed-state 0.33) => 0.15447316
(prog (st seed-state result)
(setq st (load-random-state "~/lisp/seed-state"))
(setq seed-state
(if (null st)
(ccl::initialize-mrg31k3p-state 568510646 776752825 1566514914 1437072568 929117308 264016807) ;default, can be changed
st))
(setq n (if (integerp n) n (round (* n 100))))
(dotimes (i n)
(setq result (random 1.0 seed-state)))
(return result)))

(defun rnd (&optional seed)
;(rnd) => ?
;(rnd 0.31) => 0.35242736
(if (null seed) (random 1.0) (seed-state seed)))

(defun rndm (n &optional seed)
;(rndm 6) => ?
;(rndm 5 0.23) => (0.80377346 0.5047488 0.1521786 0.5202181 0.7054099)
;(rndm 5 0.24) => (0.5047488 0.1521786 0.5202181 0.7054099 0.08438743)
(prog (out result)
(setq seed (if (null seed) seed
 (1- (if (integerp seed) seed (round (* seed 100))))))
(cond ((null seed)
 (dotimes (i n)
 (setq out (random 1.0))
 (setq result (cons out result))))
(t (dotimes (i n)
 (setq out (seed-state (incf seed)))
 (setq result (cons out result)))))
(return (nreverse result))))


--
MRAC Publishing
Janusz Podrazik

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.clozure.com/pipermail/openmcl-devel/attachments/20110612/4786c6ed/attachment.html>


More information about the Openmcl-devel mailing list