From aab5075bfe46b708135a4c353f74de5f65456449 Mon Sep 17 00:00:00 2001 From: Peter Hinch Date: Mon, 19 Dec 2016 07:31:44 +0000 Subject: [PATCH] Pseudo random number generator added --- README.md | 14 ++++++++++++++ random/random.py | 20 ++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 random/random.py diff --git a/README.md b/README.md index 3a80962..9367851 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,20 @@ There are other algorithms but this is the simplest and fastest I've encountered These were written for encoders producing TTL outputs. For switches, adapt the pull definition to provide a pull up or pull down as required. +# A pseudo random number generator + +On the Pyboard V1.1, true random numbers may be generated rapidly with pyb.rng() +which uses a hardware random number generator on the microcontroller. + +There are two use cases for the pseudo random number generator. Firstly on +platforms lacking a hardware generator (e.g. the Pyboard Lite). And secondly +where repeatable results are required, for example in testing. A pseudo random +number generator is seeded with an arbitrary initial value. On each call to the +function it will return a random number, but (given the same seed) the sequence +of numbers following initialisation will always be the same. + +See the code for usage and timing documentation. + # License Any code placed here is released under the MIT License (MIT). diff --git a/random/random.py b/random/random.py new file mode 100644 index 0000000..3362172 --- /dev/null +++ b/random/random.py @@ -0,0 +1,20 @@ +# pseudorandom numbers for MicroPython +# Uses the xorshift64star algorithm https://en.wikipedia.org/wiki/Xorshift +# Author: Peter Hinch +# Copyright Peter Hinch 2016 Released under the MIT license + +# Example usage to produce numbers between 0 and 99 +# rando = xorshift64star(100) +# successive calls to rando() will produce the required result. +# Timing 109us (Pyboard 1.1), 191us (Pyboard lite), 1.264ms (ESP8266) + +def xorshift64star(modulo, seed = 0xf9ac6ba4): + x = seed + def func(): + nonlocal x + x ^= x >> 12 + x ^= x << 25 + x ^= x >> 27 + x &= 0xffffffffffffffff + return (x * 0x2545F4914F6CDD1D) % modulo + return func