8

次のメソッドの関数を作成する必要があります。

拒否方法(一律封筒)

[a, b] でのみ fx が非ゼロであり、fx ≤ k であるとします。

  1. X から独立して X ∼ U(a, b) と Y ∼ U(0, k) を生成します (したがって、P = (X, Y ) は四角形 [a, b] × [0, k] に一様に分布します)。

  2. Y < fx(x) の場合は X を返し、それ以外の場合は手順 1 に戻ります。

    rejectionK <- function(fx, a, b, K) {
        # simulates from the pdf fx using the rejection algorithm
        # assumes fx is 0 outside [a, b] and bounded by K
        # note that we exit the infinite loop using the return statement
    
        while (TRUE) {
          x <- runif(1, a, b)
          y <- runif(1, 0, K)
          if (y < fx(x)) return(x)
       }
    }
    

なぜこれTRUEが にあるの while (TRUE)か理解できませんでした。

(y < fx(x)) が true でない場合、メソッドはループをもう一度繰り返して均一な数を再度生成することを提案します。(y < fx(x)) は true=FALSE ではありません。では、なぜ条件が にならないのwhile (FALSE)でしょうか?

繰り返しますが、どの基準で while ループに入りますか? つまり、私はこれに慣れています

   a=5 
   while(a<7){
      a=a+1
   }

ここでは、条件 (a<7) を記述する前に a を定義します。

しかしwhile (TRUE)、どのステートメントが真ですか?

さらに:

コードを実行できます

  rejectionK <- function(fx, a, b, K) {
        # simulates from the pdf fx using the rejection algorithm
        # assumes fx is 0 outside [a, b] and bounded by K
        # note that we exit the infinite loop using the return statement

        while (TRUE) {
          x <- runif(1, a, b)
          y <- runif(1, 0, K)
          cat("y=",y,"fx=",fx(x),"",y < fx(x),"\n")
          if (y < fx(x)) return(x)
       }
    }

  fx<-function(x){
     # triangular density
     if ((0<x) && (x<1)) {
       return(x)
     } else if ((1<x) && (x<2)) {
       return(2-x)
     } else {
       return(0)
     }
 }

 set.seed(123)
 rejectionK(fx, 0, 2, 1)
4

2 に答える 2

4

whileループ内で、trueまたはfalseのreturnステートメントがある場合..それに応じて機能します..

例: リストが循環しているかどうかを確認するには..

while (true) は常に true であるため、ここではループは無限ですが、return ステートメントを使用して中断することもあります。

while(true)
{
if(!faster || !faster->next)
return false;
else
if(faster==slower || faster->next=slower)
{
printf("the List is Circular\n");
break;
}
else
{
slower = slower->next;
faster = faster->next->next;
}
于 2015-04-02T04:56:39.933 に答える