【问题标题】:Conditioning a while loop (2 conditions)调节一个while循环(2个条件)
【发布时间】:2020-07-06 02:30:41
【问题描述】:

我试图在 while 循环中包含两个条件:

  1. 第一个条件是模拟次数必须至少为 50
  2. 第二个条件是 std(estimator) 必须小于 0.01.

有人可以帮助我吗?

set.seed(1)
MinSimNumber=50
Ncount=0
n=0
N=rep(0,10000)
sqrt(var(N))
while(Ncount<MinSimNumber){
  u=runif(40,0,1) #Generating a big enough vector
if(u[n+1]>u[n+2]){  #if the preceding uniform value is bigger than execute the loop
  while(u[n+1]>u[n+2]){ #while the  preceding uniform value is bigger than the following than do n=n+1
  n=n+1

  }
  n=n+2 #when the loop ends we do n=n+2 to add the first two not counted values 
}

if((u[n+1]<=u[n+2])&(n==0)) {
  n=2
}
  Ncount=Ncount+1
  N[Ncount]=n
  n=0
}

这是我的完整代码,这个模拟近似于 exp(1)

【问题讨论】:

标签: r while-loop conditional-statements


【解决方案1】:

您是否正在寻找这样的东西:

while(Ncount<100 & sqrt(var(N))<0.01)        
{        
  Ncount=Ncount+1        
  # (all my other statements...)        
}

如果你必须执行 100 步,即使 std 高于 0.01

while(sqrt(var(N))<0.01)        
{        
  if(Ncount<100)        
  {        
    Ncount=Ncount+1        
    # (all my other statements...)        
    }        
  Ncount=Ncount+1        
  # (all my other statements...)        
  }      

当然你可以在while循环之前定义“100”和“0.01”

供您编辑:

while(Ncount<100)        
{        
    Ncount=Ncount+1        
    # (all my other statements...)        
}        
if(sqrt(var(N))<0.01){TRUE}else{FALSE} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 2011-11-02
    • 2015-12-16
    • 1970-01-01
    相关资源
    最近更新 更多