LoPy4 random number method (solved)
-
Hi, just looking for the library/function to generate a random number for three choices.
like
import randomcomplains about no module.
I've tried urandom, os.random,
pyb as per this post
https://forum.micropython.org/viewtopic.php?t=2727TIA Dave
-
@pybuggz A search for "random" in the documentation reveals that link:
https://docs.pycom.io/firmwareapi/micropython/ucrypto#methods -
@pybuggz have you tried
uos.urandom(x)? http://docs.micropython.org/en/latest/library/uos.html#uos.urandom -
@dan
TNX, Looks like what I want..(note no 'u', just 'os')os.urandom(3) gives results like
>>> os.urandom(3) b'\x99\xcc\xe6'OK
os.urandom(1) gives me a single byte, and this is how to make it an integer.
I've tried:>>> print(int.from_bytes(os.urandom(1),"big")) 60I want something between 0 and 3, so I need to limit the range somehow..
Also, how do I know which Micropython functions are in 'pycompython'?
regards
Dave -
@pybuggz said in LoPy4 random number method:
n = os.urandom(1)[0]also results in a number of 0-255. To get a number of 0-3, just use
n % 4orn & 0x3. If the range you need is not a power of 2, then start with a larger random number to reduce non-randomness of the result.
What do you measn with pycompython? if you waht to know the methods of a module, import that module and call dir(module_name), e.g.import uos dir(uos)P.S.: uos is the 'Micro' version of os, and MicroPython provides os as the alias to uos.
-
@robert-hh Thanks
What I want here is to simulate some users doing 1 of 3 things, so:
>>> print(uos.urandom(1)[0] %3) 0 >>> print(uos.urandom(1)[0] %3) 0 >>> print(uos.urandom(1)[0] %3) 1 >>> >>> print(uos.urandom(1)[0] %3) 2 >>> print(uos.urandom(1)[0] %3) 2simplifies my code and will be OK.
Regarding Micropython, I've 'hacked' a bit of other code at times and this is the first time I'm having to find the functions I need, so little things like 'dir(os)' are gems.
Dave
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login