2012-07-16 125 views
4

这不是家庭作业。我想从R中的/ dev/random生成一个随机整数序列(0:9之间的50个数字)。我有一个hardware entropy key从/ dev/random生成随机整数

我已经发现了两个“点子”,这两者都不我可以得到与数字供应我,我后:

1)RDieHarder。似乎允许访问/ dev/random,但我不能让它产生我需要的整数序列。例如

>library(RDieHarder) 
>x <-dieharder(rng="/dev/urandom", psample=50) #urandom used for example 

2)accuracy package可以提供真正的随机数,但似乎是过时的,我不能看到如何从/ dev只是顺序/随机的。例如

>library(accuracy) 
>x=runifT(50) 

是的我已阅读Knuth等并了解TRNGs(因此是硬件熵键)的问题。

还有其他想法吗?谢谢。

+1

什么是您的关键生成在/ dev /随机的?随机字节(0-255)? – Spacedman 2012-07-16 14:10:01

+0

你可以找到问题中给出的超链接的所有细节。我知道它用entropy提供/ dev/random来阻止它阻塞。 – 2012-07-16 14:12:20

回答

4

以下是如何从一个开发阅读并得到n个从a到b包括:

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 
} 

如果我从/ dev /随机它会阻止阅读,因为我的系统运行的熵,但你的钥匙应该忙于喂熵进入系统,我认为......

'边缘'效应问题如下。假设我生成随机整数从0到10,但是你从0到6的整数要那么X %% 7将产生两倍多的0,1,2,3值,因为映射是这样的:

> (0:10) %% 7 
[1] 0 1 2 3 4 5 6 0 1 2 3 

现在readBin获得8位整数,这是巨大的,所以在序列结尾的奇数少数额外的数字应该没有太大的区别...

+0

我不太了解它,但它非常有趣。谢谢。 – 2012-07-16 14:19:50

+0

感谢您的注释。 V.interesting。 – 2012-07-16 14:24:25

+0

最后一个问题。如果我想从1:5开始说数字,您的代码是否容易适应?我不明白如何改变这一方面。非常感谢。 – 2012-07-16 14:36:40

1

您可以使用random程序包(它也位于CRAN),它从random.org的硬件RNG中检索数据。

R> library(random) 
R> randomNumbers(n=50,min=1,max=9,col=5) 
     V1 V2 V3 V4 V5 
[1,] 8 7 4 6 3 
[2,] 4 8 3 6 8 
[3,] 5 2 9 1 6 
[4,] 9 5 6 5 5 
[5,] 2 2 1 3 7 
[6,] 6 3 9 7 5 
[7,] 7 9 1 9 9 
[8,] 5 9 1 3 8 
[9,] 8 2 9 3 7 
[10,] 6 1 1 8 7 
R> 
+0

嗨德克。你会收到一封电子邮件。我确实看到了这一点,但我想访问/ dev/random,所以不太符合我的要求。谢谢。虽然优秀的包装。 – 2012-07-16 13:34:32

2

嗯,这是一个迟到的答案,但我发现这个通过谷歌,所以别人也可以。

这样做的代码其实很简单。 (只有两个以下行实际上是必要的。)

entropy <- file('/dev/urandom', 'rb')       #rb = read binary .. try `cat /dev/urandom` at the command line to see what this "binary" output looks like if you don't encode it rationally 
print(entropy)             #you don't need to run this but reading it will help you understand what's going on 
?readLines              #again just to explain what's going on and what the other options, like scan(), do 
readBin(entropy, what='integer')   #print random numbers from environmental noise 
set.seed(readBin(entropy,1L))    #a truly random beginning to your R session… 

在一个行:

file('/dev/urandom', 'rb') %>% readBin('integer')