Skip to content

Instantly share code, notes, and snippets.

@ivand58
Created September 1, 2019 17:22
Show Gist options
  • Save ivand58/06ad12787f6290d0fd30820f16739d29 to your computer and use it in GitHub Desktop.
Save ivand58/06ad12787f6290d0fd30820f16739d29 to your computer and use it in GitHub Desktop.
For a simple random number generator running on an embedded CPU we're unlikely to be very concerned with cycle lengths -- a cycle of 2^32-1 is perfectly acceptable. Marsaglia suggests coefficients (13, 17, 5) for a 32-bit generator.
variable seed
7 seed !
: random ( -- x ) \ return a 32-bit random number x
seed @
dup 13 lshift xor
dup 17 rshift xor
dup 5 lshift xor
dup seed !
;
: setseed ( x -- ) \ seed the RNG with x
dup 0= or \ map 0 to -1
seed !
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment