【问题标题】:Create vector of random numbers (size of vector not known at run-time)创建随机数向量(向量的大小在运行时未知)
【发布时间】:2011-10-24 19:38:11
【问题描述】:

我正在编写一个蒙特卡洛模拟程序,它应该给用户相当大的灵活性。因此,我希望用户能够指定 模拟运行前随机数的具体概率分布。但是,此时用户并不知道 需要多少个随机数。

我现在的想法是从用户那里获取一个创建一个随机数的调用对象,然后在内部根据需要创建尽可能多的这些随机数。然而, 除了循环之外,我无法获得任何其他解决方案,但感觉这是因为我错过了一些东西。所以基本上,我有 两个问题:

1) 调用对象的想法是一个好的想法吗?我还在做这个项目,所以我仍然可以更改设置,但我需要一个非常直观的 为用户提供解决方案。

2) 如果这是一个好主意,是否有更优雅的方法将随机数扩展为大小为 nrMCS 的向量?

我们举个例子:

#That's what I would get from the user with my current set-up:
rnd_call <- call("rnorm", 1, mean=0.1, sd=0.01)
#To create nrMCS random numbers, that's my best shot so far:
nrMCS <- 100
rnd_vec <- as.numeric(nrMCS)
for (i in 1:nrMCS){rnd_vec[i] <- eval(rnd_call)}
rnd_vec
[1] 0.09695170 0.11752132 0.11548925 0.11205948 0.10657986 0.12017120 0.09518435
...
#Question: Is there are more elegant way?
#I tried the following, but it fails for certain reasons
rep(eval(rnd_call), nrMCS) #DOES NOT WORK: Repeats ONE random number
[1] 0.1105464 0.1105464 0.1105464 0.1105464 0.1105464 0.1105464 0.1105464 0.1105464 
...
eval(rep(rnd_call, nrMCS)) #DOES NOT WORK
Error in rnorm(1, mean = 0.1, sd = 0.01, rnorm, 1, mean = 0.1, sd = 0.01,  : 
formal argument "mean" matched by multiple actual arguments

【问题讨论】:

  • 做你想做的事(虽然我认为我下面的解决方案更好)你应该使用replicate(nrMCS,eval(rnd_call))而不是rep(...)

标签: r


【解决方案1】:

我认为更惯用的方法是采用r* 函数和参数列表。只要您可以避免致电eval,您就应该这样做。像这样的:

rnd_fun <- rnorm
rnd_args <- list(mean=0.1,sd=0.01)
nrMCS <- 100
rnd_vec <- do.call(rnd_fun,c(list(n=nrMCS),rnd_args))

(这依赖于 R 中的约定,即 r*(随机偏差生成器)函数的 first 参数始终为 n,所需偏差的数量...)

此外,使用n=nrMCS 调用rnd_fun 一次通常比调用nrMCS 次更有效...

library(rbenchmark)
nrMCS <- 10000
benchmark(single_call=do.call(rnd_fun,c(list(n=nrMCS),rnd_args)),
           mult_call=replicate(nrMCS,do.call(rnd_fun,c(list(n=1),rnd_args))))
         test replications elapsed relative user.self sys.self 
2   mult_call          100  11.135 91.27049    11.084    0.004 
1 single_call          100   0.122  1.00000     0.080    0.036

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    相关资源
    最近更新 更多