开发者

Warning "the condition has length > 1 and only the first element will be used"

开发者 https://www.devze.com 2023-01-29 06:21 出处:网络
My R code: bnc1<-function(maxITR=100000, d=2, l=1){ counts=0; for (i in 1:maxITR){ x=runif(1,0,pi); y=runif(2,0,d/2);

My R code:

bnc1<-function(maxITR=100000, d=2, l=1){
    counts=0;
    for (i in 1:maxITR){
        x=runif(1,0,pi);
        y=runif(2,0,d/2);
        if ((l/2*sin(x)) >= y) counts=counts+1;
    } 
    counts/maxITR*d/l
}

Running the code:

> bnc1(maxITR=1000)
[1] 0.652
There were 50 or more warnings (use warnings() to see the first 50)
> warnings()
Warning messages:
1: In if ((l/2 * sin(x)) >= y) counts = counts + 1 ... :
  the condition has length > 1 and only the first element will be used
2: In if ((l/2 * sin(x)) >= y) counts = counts + 1 ... :开发者_JAVA技巧
  the condition has length > 1 and only the first element will be used
...
49: In if ((l/2 * sin(x)) >= y) counts = counts + 1 ... :
  the condition has length > 1 and only the first element will be used
50: In if ((l/2 * sin(x)) >= y) counts = counts + 1 ... :
  the condition has length > 1 and only the first element will be used

Does anyone has an idea what causes the warnings?


runif returns a vector.

if takes a single value (not a vector).

Check the manual for runif, I don't think you are using it right.


In R, it often makes sense to remove for loops and use vectors instead - for example:

bnc1<-function(maxITR=100000, d=2, l=1){
    x=runif(maxITR,0,pi);
    y=runif(maxITR,0,d/2);
    counts = sum((l/2*sin(x)) >= y);
    counts/maxITR*d/l
}
0

精彩评论

暂无评论...
验证码 换一张
取 消