kopia lustrzana https://github.com/peterhinch/micropython-samples
Pseudo random number generator added
rodzic
e7d3fb4b8c
commit
aab5075bfe
14
README.md
14
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).
|
||||
|
|
|
@ -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
|
Ładowanie…
Reference in New Issue