Versionsvergleich
Aus ProgrammingWiki
Vergleich: 2012-10-01T21:54:03+00:00 → 2012-10-02T09:17:05+00:00
<language>Scheme</language> | |
| + | <code id="506ab110a0409" hidden> |
| + | (define random-maker |
| + | (let* ((multiplier 48271) |
| + | (modulus 2147483647) |
| + | (apply-congruence |
| + | (lambda (current-seed) |
| + | (let ((candidate (modulo (* current-seed multiplier) modulus))) |
| + | (if (zero? candidate) |
| + | modulus |
| + | candidate)))) |
| + | (coerce |
| + | (lambda (proposed-seed) |
| + | (if (integer? proposed-seed) |
| + | (- modulus (modulo proposed-seed modulus)) |
| + | 19860617)))) ;; an arbitrarily chosen birthday |
| + | (lambda (initial-seed) |
| + | (let ((seed (coerce initial-seed))) |
| + | (lambda args |
| + | (cond ((null? args) |
| + | (set! seed (apply-congruence seed)) |
| + | (/ (- modulus seed) modulus)) |
| + | ((null? (cdr args)) |
| + | (let* ((proposed-top |
| + | (ceiling (abs (car args)))) |
| + | (exact-top |
| + | (if (inexact? proposed-top) |
| + | (inexact->exact proposed-top) |
| + | proposed-top)) |
| + | (top |
| + | (if (zero? exact-top) |
| + | 1 |
| + | exact-top))) |
| + | (set! seed (apply-congruence seed)) |
| + | (inexact->exact (floor (* top (/ seed modulus)))))) |
| + | ((eq? (cadr args) 'reset) |
| + | (set! seed (coerce (car args)))) |
| + | (else |
| + | (display "random: unrecognized message") |
| + | (newline)))))))) |
| + | |
| + | ;(define random |
| + | ; (let ((seed (time-nanosecond (current-time)))) |
| + | ; (display seed) |
| + | ; (random-maker seed))) |
| + | |
| + | (require-library 'sisc/libs/srfi/srfi-19) |
| + | (import srfi-19) ; stellt current-time usw. bereit |
| + | |
| + | (define random (random-maker (time-nanosecond (current-time)))) |
| + | </code> |
| + | |
<run id="5069703a883cb"> | |
(equal? #\u #\u) | |
</run> | |
<check> | |
(equal? #\u #\u) | |
</check> | |
<run id="506a10fabfde2"> | |
(equal? 'g 'g) | |
</run> | |
<check> | |
(equal? 'g 'g) | |
</check> | |
| + | |
| + | === Zufallstest === |
| + | |
| + | <code id="506ab110a046a"> |
| + | (define random-test |
| + | (lambda (n max) |
| + | (if (= max 0) |
| + | 'ok |
| + | (let [(z (random n))] |
| + | (if (or (< z 0) (> z (- n 1))) |
| + | (list z 'error) |
| + | (random-test n (- max 1))))))) |
| + | </code> |
| + | |
| + | <run id="506ab110a04db"> |
| + | (random-test 10 1000) |
| + | </run> |