RuudB wrote: ↑Sat Jun 01, 2019 2:54 am
Thank you so much!
It did cost me so much time but its finally starting to work out haha! So simple but you have to know ..
pfletch101 wrote: ↑Fri May 31, 2019 3:10 pm
This treats the binary file or the output of the urandom device as a byte stream (which is basically what it is - actually a
bit stream). I think that the OP may be looking for a sequence of discrete random numbers - though he needs to specify the range in which these should lie.
Yes, that is right, preferable I need random numbers in the range 0 to 9
If that is possible that would really be what I need!
So once more I will polity ask for your help!
Thanks in advance! And have a great weekend!
Here is (Python 3) code to print sequential random single-digit numbers:
Code: Select all
from time import sleep
f=open('/dev/urandom','rb')
while True:
rndbytes=f.read(1)
rndint=rndbytes[0]
if rndint < 10: # ignore numbers above 9 - should not disturb randomness of remainder
print (rndint) # this can be replaced by code which uses the random number
sleep(1)
Here, probably more usefully

is a function to return a random number between 0 and 9.
Code: Select all
def randint09():
with open('/dev/urandom','rb') as f:
while True:
rndbytes=f.read(1)
rndint=rndbytes[0] & 15 # mask off high bits (added in edit)
if rndint < 10: # ignore numbers above 9 - should not disturb randomness of remainder
return rndint
# the following code uses the function to generate random integers to print to the screen
while True:
print(randint09())
sleep(1) # assumed to have been imported
It is better to use the urandom device directly than to generate a file and use that, since, in the latter case, you will always see the same sequence. The function could easily be generalized to generate numbers in any specified range - for ranges extending beyond 255, bytes would be read and combined two (or more) at a time to get the initial random integer - then you can throw away anything outside the desired range.
{EDIT} The commented change in the randint09 function should not change the validity of the code but it will make it quite a bit faster/more efficient, since only (on average) 6 out of 16 of the original random bytes will be discarded, needing at least one additional 'try', while without the masking step, many more 'tries' to get a 'hit' will be necessary for some original sequences. Obviously, different integer ranges for the random output would require the use of appropriate masks.