A function to get random numbers on Linux

Started by TedWalther, December 06, 2016, 09:28:51 PM

Previous topic - Next topic

TedWalther

I developed this function for some population simulations I'm running.  Newlisp has a nice built-in random number generator.  But I wanted a bit more randomness than that provides.  So I wrote this function to access the urandom device on Linux, which gives you lots of pretty good random numbers, fast.



(context '/dev/urandom)
(define max-32bit-int 4294967295)
(define fd (open "/dev/urandom" "read"))
(define /dev/urandom:/dev/urandom
  (lambda ()
    (let (random-value nil buf nil)
      (when fd
        (read fd buf 4)
        (set 'random-value (div (max 1 (first (unpack "lu" buf))) max-32bit-int)))
      random-value)))
(context MAIN)


Examples of usage:

> (/dev/urandom)
0.4954840036797067
> (/dev/urandom)
0.93390936822023


If you want really random numbers, change /dev/urandom to /dev/random everywhere in the function.  If you do that though, sometimes you will get nil as an answer, because the system didn't have enough time to build up enough "real" randomness.  That is why I switched to urandom; it gives a reasonably random number every single time, and fast.  But whenever real randomness is available, urandom uses it too.



Presumably this will work on BSD and Mac OSX, with minor or no modifications.
Cavemen in bearskins invaded the ivory towers of Artificial Intelligence.  Nine months later, they left with a baby named newLISP.  The women of the ivory towers wept and wailed.  \"Abomination!\" they cried.