2010-12-06 53 views
1

My R Code:Warnung "die Bedingung hat Länge> 1 und nur das erste Element wird verwendet"

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 
} 

Ausführen des 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 ... : 
    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 

Hat jemand eine Idee hat, was die Ursachen Warnungen?

Antwort

6

runif gibt einen Vektor zurück.

if nimmt einen einzelnen Wert (kein Vektor).

Überprüfen Sie das Handbuch für runif, ich glaube nicht, dass Sie es richtig verwenden.


In R, macht es oft Sinn für Schleifen und Verwendung Vektoren anstatt zu entfernen - zum Beispiel:

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

Dank! y = runif (2,0, d/2) sollte y = runif (1,0, d/2) sein. – Tim

+0

Okay, hört sich an, als hättest du eine Lösung. Vielleicht finden Sie mein Beispiel ist eine sinnvolle Vereinfachung. –

+0

Danke! Ihr Code ist viel effizienter! – Tim

Verwandte Themen