gpt4 book ai didi

r - 生成随机 bool 向量的最快方法

转载 作者:行者123 更新时间:2023-12-04 11:03:53 24 4
gpt4 key购买 nike

给定一个概率矢量p,一种快速的方法是生成一个长度与x相同且具有独立元素的随机 bool 矢量p,这样每个x[i]==TRUEp[i]的概率为i

具体来说,有没有比这些方法更快的方法?:

p <- rep(0.5,10e6)

system.time(runif(length(p)) < p)
user system elapsed
0.36 0.02 0.37

system.time(rbinom(length(p),1,p)>0)
user system elapsed
1.14 0.04 1.17

最佳答案

在我的机器上使用sample函数更快:

system.time(runif(length(p)) < p)
user system elapsed
0.315 0.002 0.318
system.time(sample(c(TRUE,FALSE), 10e6, TRUE))
user system elapsed
0.2 0.0 0.2

关于r - 生成随机 bool 向量的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32886676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com