A function to get random numbers on Linux

Q&A's, tips, howto's

A function to get random numbers on Linux

Postby TedWalther » Wed Dec 07, 2016 5:28 am

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.

Code: Select all
(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:
Code: Select all
> (/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.
TedWalther
 
Posts: 602
Joined: Mon Feb 05, 2007 1:04 am
Location: Abbotsford, BC

Return to newLISP in the real world

Who is online

Users browsing this forum: No registered users and 1 guest

cron