【问题标题】:Calculating the mean of 200 iterations for my R Code为我的 R 代码计算 200 次迭代的平均值
【发布时间】:2021-03-12 15:58:37
【问题描述】:

问题:

通过生成 10,000 对样本,求 2 个随机选择的整数互质(互质)的概率。 我已经能够找到 2 个数字是否互质,但不知道如何找到 200 次迭代的平均值。我想我应该使用 for 循环,但不确定如何去做。

这是我目前想出的:


x1<- sample(1:10000,1)
x1
x2<- sample(1:10000,1)
x2
coprime(x1,x2)
result = coprime(x1,x2)
print(result)

【问题讨论】:

  • 使用mean(times.coprime),其中times.coprime是一个逻辑向量,只要你找到两个互质整数times.coprime &lt;- sapply(integer(200L), rand.coprime),其中rand.coprime对两个数字进行采样并返回result,它就为真

标签: r for-loop mean primes sample


【解决方案1】:

如果使用replicate 函数,则不需要循环:

trials <- 10000
results <- replicate(trials, coprime(sample(1:10000, 1), sample(1:10000, 1)))
sum(results/trials)

每次运行分析时,该值都会略有变化,因为它每次都基于绘制伪随机数。或者,您可以绘制所有数字,然后使用 mapply 计算结果,这可能会更快。

results <- mapply(coprime, sample(1:10000, 10000, replace=TRUE), sample(1:10000, 10000, replace=TRUE))
sum(results)/trials

【讨论】:

    猜你喜欢
    • 2015-11-15
    • 1970-01-01
    • 2017-07-07
    • 2014-04-01
    • 1970-01-01
    • 2022-11-12
    • 2022-06-28
    • 1970-01-01
    • 2021-08-11
    相关资源
    最近更新 更多