random.scm 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. ; Copyright (c) 1993-2007 by Richard Kelsey and Jonathan Rees. See file COPYING.
  2. ; Random number generator, extracted from T sources. Original
  3. ; probably by Richard Kelsey.
  4. ; Tests have shown that this is not particularly random.
  5. (define half-log 14)
  6. (define full-log (* half-log 2))
  7. (define half-mask (- (arithmetic-shift 1 half-log) 1))
  8. (define full-mask (- (arithmetic-shift 1 full-log) 1))
  9. (define index-log 6)
  10. (define random-1 (bitwise-and 314159265 full-mask))
  11. (define random-2 (bitwise-and 271828189 full-mask))
  12. ; (MAKE-RANDOM <seed>) takes an integer seed and returns a procedure of no
  13. ; arguments that returns a new pseudo-random number each time it is called.
  14. ; <Seed> should be between 0 and 2**28 - 1 (exclusive).
  15. (define (make-random seed)
  16. (if (and (integer? seed)
  17. (< 0 seed)
  18. (<= seed full-mask))
  19. (make-random-vector seed
  20. (lambda (vec a b)
  21. (lambda ()
  22. (set! a (randomize a random-1 random-2))
  23. (set! b (randomize b random-2 random-1))
  24. (let* ((index (arithmetic-shift a (- index-log full-log)))
  25. (c (vector-ref vec index)))
  26. (vector-set! vec index b)
  27. c))))
  28. (call-error "invalid argument" make-random seed)))
  29. (define (randomize x mult ad)
  30. (bitwise-and (+ (low-bits-of-product x mult) ad)
  31. full-mask))
  32. (define (make-random-vector seed return)
  33. (let* ((size (arithmetic-shift 1 index-log))
  34. (vec (make-vector size 0)))
  35. (do ((i 0 (+ i 1))
  36. (b seed (randomize b random-2 random-1)))
  37. ((>= i size)
  38. (return vec seed b))
  39. (vector-set! vec i b))))
  40. ; Compute low bits of product of two fixnums using only fixnum arithmetic.
  41. ; [x1 x2] * [y1 y2] = [x1y1 (x1y2+x2y1) x2y2]
  42. (define (low-bits-of-product x y)
  43. (let ((x1 (arithmetic-shift x (- 0 half-log)))
  44. (y1 (arithmetic-shift y (- 0 half-log)))
  45. (x2 (bitwise-and x half-mask))
  46. (y2 (bitwise-and y half-mask)))
  47. (bitwise-and (+ (* x2 y2)
  48. (arithmetic-shift (bitwise-and (+ (* x1 y2) (* x2 y1))
  49. half-mask)
  50. half-log))
  51. full-mask)))