PasteRack.org
Paste # 83135
2017-11-06 09:25:17

Fork as a new paste.

Paste viewed 667 times.


Embed:

Random numbers and Random Sanity

  1. ; more info: http://gus-massa.blogspot.com/2017/11/testing-random-numbers-in-racket-with.html
  2.  
  3. #lang racket
  4.  
  5. (require #;net/http-client
  6.          file/sha1
  7.          racket/random)
  8.  
  9. ;Auxiliary function to create a random bytes
  10. (define (random-bytes n)
  11.   (list->bytes
  12.    (for/list ([i (in-range n)])
  13.     (random 256))))
  14.  
  15. ;Evaluate body with a fixed seed
  16. (define-syntax-rule (with-random-seed seed body ...)
  17.   (parameterize ([current-pseudo-random-generator (make-pseudo-random-generator)])
  18.     (random-seed seed)
  19.     body ...))
  20.  
  21. (displayln (random 10))    ; ==> 3?
  22. (with-random-seed 1234567890
  23.   (displayln (random 10))  ; ==> 1
  24.   (displayln (random 10))) ; ==> 5
  25. (displayln (random 10))    ; ==> 2?
  26. (with-random-seed 1234567890
  27.   (displayln (random 10))  ; ==> 1
  28.   (displayln (random 10))) ; ==> 5
  29. (displayln (random 10))    ; ==> 5?
  30.  
  31. ;Test in Random Sanity
  32. ;Disabled in PasteRack
  33. #;(define (test-random-bytes b)
  34.     (let-values ([(status headers content)
  35.                   (http-sendrecv "rest.randomsanity.org"
  36.                                  (string-append "/v1/q/" (bytes->hex-string b)))])
  37.       (let ([text (port->string content)])
  38.         (cond
  39.           [(string=? text "true") #t]
  40.           [(string=? text "false") #f]
  41.           [else (raise-result-error 'test-random-bytes "true or false" text)]))))
  42.  
  43. #;(test-random-bytes (make-bytes 64 0))
  44. #;(with-random-seed 1234567890
  45.     (test-random-bytes (random-bytes 64)))
  46. #;(test-random-bytes (random-bytes 64))
  47. #;(test-random-bytes (crypto-random-bytes 64))
  48.  
  49. ;Show some examples of "random" bytes instead
  50. (make-bytes 8 0)         ; ==> #"\0\0\0\0\0\0\0\0"
  51. (with-random-seed 1234567890
  52.   (random-bytes 8))      ; ==> #"%\202\372\216\351u\274\231"
  53. (random-bytes 8)         ; ==> #"\17:x4\216\300W\300" ????
  54. (crypto-random-bytes 8)  ; ==> #"~\204\235P\3639#\26" ????
  55.  
  56.  
  57.  

=>

4

1

5

0

1

5

7

#"\0\0\0\0\0\0\0\0"

#"%\202\372\216\351u\274\231"

#"\370\354v\243\253\243\212\206"

open-input-file: `read' access denied for /dev/urandom