[SOLVED] How to get random number in a range
-
This post is deleted! -
You should look at urandom. It gives you a random number within the byte size you pass into the function. This gives you a good value to scale with. I cannot remember how "good" this is for random numbers, especially for cryptography, but probably good enough for many cases.
You could do something simple, don't judge, quickly typing this without testing and to prove a point. This is not best practice.
the_range = 41-40
result = uos.urandom(1) / 256 * the_rangehttps://docs.pycom.io/pycom_esp32/library/uos.html#uos.urandom
-
@TravisT said in How to get random number in a range:
result = uos.urandom(1) / 256 * the_range
Thanks for your reply, it gives me this error:
TypeError: unsupported types for truediv: 'bytes', 'int'
-
@amartinez you could code as follows:
import uos result = (uos.urandom(1)[0] / 256) + 40Which will give you a number between 40.0 and 40.99609375. Since you started with a byte, there are only 256 different values.
-
@amartinez
based on my old post
https://forum.pycom.io/topic/1110/random-number-generator/2def Random(): r = crypto.getrandbits(32) return ((r[0]<<24)+(r[1]<<16)+(r[2]<<8)+r[3])/4294967295.0 def RandomRange(rfrom, rto): return Random()*(rto-rfrom)+rfrom -
@robert-hh @livius thank you so much!
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