[SOLVED] How to get random number in a range
-
This post is deleted!
-
@robert-hh @livius thank you so much!
-
@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
-
@amartinez you could code as follows:
import uos result = (uos.urandom(1)[0] / 256) + 40
Which will give you a number between 40.0 and 40.99609375. Since you started with a byte, there are only 256 different values.
-
@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'
-
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