0

CPX: Random number generator not random
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

CPX: Random number generator not random

by smagoun on Sun Jan 24, 2021 10:07 am

The random number generator for the Circuit Playground Express in MakeCode isn't truly random. It's always initialized with the same seed, so you'll get the same sequence of "random" numbers each time you boot the CPX. For example a simple program that prints 20 random numbers in the range 0-10:

Code: Select all | TOGGLE FULL SIZE
input.buttonB.onEvent(ButtonEvent.Click, function () {
    for (let i = 0; i < 20; i++) {
        console.log(Math.randomRange(0, 10))
    }
})

...will always start:
0,6,0,6,0,0,1,9,4,2,10,3,10,3,8,10,10,5,3,2

I don't have the hardware to test, but it looks like this is true for all SAMD21 boards (like CPX) in MakeCode. See the initRandomSeed() implementation here; the seed is fixed:
https://github.com/microsoft/pxt-common ... m.cpp#L121

As a workaround I made a function that uses the light + sound sensors to add entropy:
Code: Select all | TOGGLE FULL SIZE
let rand = 0
function getRandom(min: number, max: number): number {
    rand = Math.randomRange(0, 255)
    rand = rand + input.soundLevel()
    rand = rand + input.lightLevel()
    rand = rand / 3
    rand = Math.round((rand % (max - min)) + min)
    return rand
}

It's not perfect (for example it's only for random numbers in the range 0-255), but I figured I'd post it here in case anyone else needs more randomness from the CPX.

There's an open issue in GitHub: https://github.com/microsoft/pxt-adafruit/issues/1179

smagoun
 
Posts: 11
Joined: Sun Feb 11, 2018 5:35 pm

Re: CPX: Random number generator not random

by adafruit_support_carter on Mon Jan 25, 2021 3:29 pm

Yep, that's the expected behavior. There is no hardware true random number generator. Seeding with sensor noise is a good work around. Some discussion about this here:
https://learn.adafruit.com/circuit-play ... dom-or-not

adafruit_support_carter
 
Posts: 20584
Joined: Tue Nov 29, 2016 2:45 pm

Please be positive and constructive with your questions and comments.