microbit-foundation / micropython-microbit-v2

Temporary home for MicroPython for micro:bit v2 as we stablise it before pushing upstream
MIT License
45 stars 25 forks source link

Random number generator is not generating random numbers. #53

Closed mytechnotalent closed 3 years ago

mytechnotalent commented 3 years ago
import random

random_number = random.randint(1, 20)
print(random_number)

It is printing the same one random number. In this case it is 7 @microbit-carlos as we discussed.

carlosperate commented 3 years ago

uBit.init should be seeding the random number generator: https://github.com/microbit-foundation/micropython-microbit-v2/blob/0c4287ca33702f85917bd706067a6ca41a21510f/src/codal_app/main.cpp#L52-L53 https://github.com/lancaster-university/codal-microbit-v2/blob/d49c441bb712bc02bf2c7e4d95b757721eb54e4a/model/MicroBit.cpp#L169

dpgeorge commented 3 years ago

It is printing the same one random number.

Do you mean it prints the same number each time it starts up? Calling randint() again and again should return different values.

Note that the random module uses its own pseudo-RNG, not anything from CODAL.

mytechnotalent commented 3 years ago

@dpgeorge when I literally reboot the micro:bit it picks the same number every time. Yes when it starts up. I was hoping we can avoid having to call randint() twice if possible.

dpgeorge commented 3 years ago

Ok. I think the issue is that the random module uses the same PRNG sequence each time it starts up. This needs to be fixed so that it seeds itself from a true random source.

mytechnotalent commented 3 years ago

Any progress on this? I am working on many micro:bit tutorials but the random number generator is failing as stated?

dpgeorge commented 3 years ago

This should be fixed by b621de7b349d248bdaea4a551fd75d956a1bbe27 (I was not able to test it).

jaustin commented 3 years ago

@mytechnotalent Does the 'thumbs up' mean it works for you? Just want to be explicit before I close the issue, or go to test it myself :)

mytechnotalent commented 3 years ago

@jaustin my apologies! I did git checkout b621de7 and compile and test...

>>> randint(1, 5)
1
>>> randint(1, 5)
4
>>> randint(1, 5)
5
>>> randint(1, 5)
2
>>> 

@dpgeorge change did in fact fix. This is tested and good to merge to main.