2016-05-03 14 views
0

誰かが私がCで書いたコードを見て助けることができますか?それは数字を生成することができますが、if条件は間違っているように見えますが、修正する方法はわかりません。forループとWhileループでCの値を選択する

Iは、分布のいくつかのN個の乱数値を取得する必要があり、これらの値は、特別な間隔であるので、私は以下のようにforループを使用:

gasdev()はランダム値を生成する関数である
n=10; mu=2; mu_plus=3; p=0.2; 

    for(i=1; i<=n; i++) 
    { 
    x1 = gasdev(&idum); 
    x2 = gasdev(&idum); 
    z = sqrt(1-p*p)*x1 + p*x2 + mu; 
    z_p= x2 + mu_plus; 

    if (z > 2.17 || z<-2.17) 
    { 
     Z[i]=z; 
     Z_plus[count]=z_p; 
    } 
    printf("%d %lf %lf\n", i, Z[i], Z_plus[i]); 
} 

標準正規分布ZとZ_plusは1 * nベクトルです。結果は混乱しているので、IF条件が間違っていなければならないと思います。誰も私を助けることができますか?ありがとうございました。

また、私はWhileループを試しました。

while(count < n) 
    { 
     x1 = gasdev(&idum); 
     x2 = gasdev(&idum); 
     z = sqrt(1-p*p)*x1 + p*x2 + mu; 
     z_p= x2 + mu_plus; 

    if (z > 2.17 || z<-2.17) 
    { 
     count++;   
     Z[count]=z; 
     Z_plus[count]=z_p; 
    } 
    printf("%d %lf\n",count, Z[count]); 

    if (count >n) break; 
    } 

正常に印刷できますが、最後にエラーが発生します。

ありがとうございました!

+1

あなたは '+/- 2.17'間' z'を拘束しようとしていませんでしょうか? –

+0

BTW: '(1-p)*(1 + p)'は '1-p * p'よりも安定した数値です。 '| p |'が '1'に近いとき、コードはより良い答えを得るでしょう。 – chux

+0

いいえ2.17より大きい値または-2.17より小さい値を選択しようとしています。 – Yanyan

答えて

1

ここでのエラーは、zが括弧セットの範囲外の場合、Z配列に値を入れないように、常にforループの一部としてiをインクリメントすることです。あなたはカウントを指定していないので、私はそうなったのでしょうか?

n=10; mu=2; mu_plus=3; p=0.2; 

    for(i=1; i<=n; i++) 
    { 
     x1 = gasdev(&idum); 
     x2 = gasdev(&idum); 
     z = sqrt(1-p*p)*x1 + p*x2 + mu; 
     z_p= x2 + mu_plus; 

     if (z > 2.17 || z<-2.17) 
     { 
      Z[i]=z; 
      Z_plus[count]=z_p; // Should this be Z_plus[i] ?? 
     } 
     // Note that if outside of bracket no value put in Z[i] 
     // This makes Z[i] and Z_plus[i] garbage 
     printf("%d %lf %lf\n", i, Z[i], Z_plus[i]); 
    } 

あなたのwhileループが修正されていないか、それがn-1であり、あなたがサイズnの配列として定義されている必要があることを表示されたときにZ [n]を処理しようとすると、それは(最大インデックスをカウントをインクリメントしてn-1)である。また、印刷物は外側になければならない。

while(count < n) 
    { 
     x1 = gasdev(&idum); 
     x2 = gasdev(&idum); 
     z = sqrt(1-p*p)*x1 + p*x2 + mu; 
     z_p= x2 + mu_plus; 

     if (z > 2.17 || z<-2.17) 
     { 
     // This allows count == n which overflows the buffer. 
     count++;   
     Z[count]=z; 
     Z_plus[count]=z_p; 
     } 

    // This should be inside the bracket not outside 
    printf("%d %lf\n",count, Z[count]); 

    // This is not needed since it will exit the while at count == n 
    if (count >n) break; 
    } 

正しいコードは

count = 0; 
    while(count < n) 
    { 
     x1 = gasdev(&idum); 
     x2 = gasdev(&idum); 
     z = sqrt(1-p*p)*x1 + p*x2 + mu; 
     z_p= x2 + mu_plus; 

     if (z > 2.17 || z<-2.17) 
     { 
     Z[count]=z; 
     Z_plus[count]=z_p; 
     printf("%d %lf\n",count, Z[count]); 
     count++;   
     } 
    } 
+0

ありがとうございます。できます。 – Yanyan

関連する問題