CPX: Random number generator not random

Microsoft's MakeCode platform for easy blocks-style programming

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
smagoun
 
Posts: 11
Joined: Sun Feb 11, 2018 5:35 pm

CPX: Random number generator not random

Post by smagoun »

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

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

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

User avatar
adafruit_support_carter
 
Posts: 29056
Joined: Tue Nov 29, 2016 2:45 pm

Re: CPX: Random number generator not random

Post by adafruit_support_carter »

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

Locked
Please be positive and constructive with your questions and comments.

Return to “MakeCode”