【问题标题】:While loop ends although condition is not fully achieved虽然条件未完全实现,但循环结束
【发布时间】:2022-12-17 23:12:37
【问题描述】:

我正在使用下面的代码来查找使置信区间变为大约 25 所需的迭代次数。但是,当我运行它时,它会以不符合标准的区间长度停止。它们很接近,但不在 24.99 和 25.01 之间。

counter <- 0
r <- 50
while((r-25)>0.01){
    counter <- counter + 1
    a <- replicate(500,profit())
    CI_l <- mean(a) - (sd(a)/sqrt(500))*qnorm(0.975)
    CI_u <- mean(a) + (sd(a)/sqrt(500))*qnorm(0.975)
    r <- CI_u-CI_l
}
cat("It took ", counter, " tries to get to an interval of", r)

我确信还有更简单的方法可以做到这一点,但我主要担心的是 R 是否做错了,或者我做错了。

【问题讨论】:

  • 请编辑您的问题以确保可重复性。 Error in profit() : could not find function "profit"

标签: r loops


【解决方案1】:

r 远低于 25 时,(r-25) 远低于 0.01,因此 while 条件为假并结束。

r <- 1
(r-25)
# [1] -24
(r-25) > 0.01
# [1] FALSE

使用abs(.)

abs(r-25) > 0.01
# [1] TRUE

导致

while(abs(r-25) > 0.01){
  # ...
}

我赞赏在不平等测试中使用宽容;通常第一次尝试是while (r != 25),但根据Why are these numbers not equal?R FAQ 7.31,它可能永远不会发生(即使r非常接近25)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 2011-12-03
    • 2021-11-13
    • 1970-01-01
    相关资源
    最近更新 更多