This is not homework. I would like to generate a random integer sequence (50 digits between 0:9) from /dev/random in R. I have a hardware entropy key.
I have found two "ideas", neither of which I can get to supply me with the numbers I am after:
1) RDieHarder. Seems to allow access to /dev/random, but I cannot get it to produce the integer sequence that I require. e.g.
>library(RDieHarder)
>x <-dieharder(rng="/dev/urandom", psample=50) #urandom used for example
2) The accuracy package can supply true random numbers, but appears to be out of date and I can't see how to just sequence from /dev/random. e.g.
>library(accuracy)
>x=runifT(50)
Yes I have read Knuth etc and understand the problems of TRNGs (hence the hardware entropy key).
Any other ideas? Thanks.
Here's how to read from a dev and get n numbers from a to b inclusive:
readRandom <- function(n,a,b,dev="/dev/urandom"){
size = b-a + 1
rng = file(dev,"rb") # open connection
nums = readBin(rng,what="integer",n=n) # read some 8-byte integers
close(rng) # close the connection
return( a + nums %% size ) # reduce range and shift
}
If I read from /dev/random it blocks since my system runs out of entropy, but your key should be busy feeding entropy into the system, I think....
The 'edge' effect problem is as follows. Suppose I generate random integers from 0 to 10, but you want integers from 0 to 6. Then X %% 7 would generate twice as many 0,1,2,3 values, because the mapping is this:
> (0:10) %% 7
[1] 0 1 2 3 4 5 6 0 1 2 3
Now readBin is getting 8-bit integers, which are huge, so the odd few extra numbers at the end of the sequence shouldn't make much difference...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With