2017-05-09 77 views
0

我有一個隨機函數,根據某些區間的可能性給出數字。rand()在循環中給出相同的結果

int myrand (float array[]){ //this function gives an interval according to 
          // possibilities 


    float possib[part]; 
    int i; 
    float r; 
    possib[0]=array[3]; 
    for (i=1;i<part;i++) 
     possib[i]=possib[i-1]+array[i+3]; 
    r=(float)rand()/32767; 
    printf(" r= %f ",r); //this is to check whether r is different in every run 

    for(i=0;i<part;i++){ 
     if(r<possib[i]){ 
      return i; 
      break; 
     } 
    } 

} 

double myrandfinal(float array[],int n){ //this function gives a random 
    double final; //double in the chosen interval 
    final=array[n]+(((float)rand()/32767)*(array[n]-array[n-1])); 
    printf("final= %f",final-array[n]); //again to check 
    return final; 
} 

float eval() { 
    float l; 
    float interval[]={3.25,4.00,4.75,5.50}; 
    float flar[]={0.1,0.25,0.15,0.5}; 

     l=myrandfinal(interval,myrand(flar)); 
    return 3+l; 

} 

在主,我有類似以下內容:

int main(){ 
    int i; 
    srand(time(NULL)); 
    for(i=0;i<10;i++) 
     printf("%f",eval()); //the evaluate function 
} 

的問題是,當我期待的oputput像:

6.50 
7.25 
7.60 
... 

我得到的輸入,如:

6.50 
6.50 
6.50 
... 

雖然我ge在所有檢查中不同的數字,評估函數的結果是相同的。在主當我剛寫

printf("%f",eval()); 

未經環和執行自己的幾次,我得到不同的結果。這是什麼原因?

對不起,我的錯誤,我是新用戶,我試圖去適應它:)

+4

'eval()'定義在哪裏? – Marievi

+0

@Marievi它被定義爲'myrand()'和'myrandfinal()',因爲它太長和複雜,我沒有寫它。它對這個問題有不相干的部分。 – NoWay

+6

'eval'是你問我們的功能,所以我認爲它是完全相關的。請向我們展示一個[最小,完整和可驗證的示例](https:// stackoverflow。com/help/mcve),包括你得到的輸出(以及你期望的結果)。 –

回答

0

出界UB

float eval() { 
    float flar[] = {0.1, 0.25, 0.15, 0.5}; 
    // ... 
    ... myrand(flar) ... 
} 

而在被調用的函數您嘗試訪問不存在的元件

int myrand (float array[]) { 
    // ... 
    for (i = 1; i < part; i++) 
     possib[i] = possib[i - 1] + array[i + 3]; 
     //       ^^^^^^^^^^^^ 
} 
+0

flar []在原代碼中有部分+3個元素,我以這個爲例。但是,是的,這是在其他地方出界。非常感謝。 – NoWay

0

由於我們沒有看到所有相關的代碼,我們只能猜測。兩個原因(計算使用)rand()收率常數值:

  • 重複調用srand()函數使用相同的參數
  • 整數操作,就像分割截去小數部分或(例如)產生總是0
0

代碼已經在myrand()

代碼後使用myrand(flar)導致不確定的行爲缺少返回路徑。

int myrand(float array[]) { //this function gives an interval according to possibilities 
    float possib[part]; 
    int i; 
    float r; 
    possib[0] = array[3]; 
    for (i = 1; i < part; i++) 
    possib[i] = possib[i - 1] + array[i + 3]; 
    r = (float) rand()/32767; 
    printf(" r= %f ", r); //this is to check whether r is different in every run 

    for (i = 0; i < part; i++) { 
    if (r < possib[i]) { 
     return i; 
     break; 
    } 
    } 
    // NO RETURN VALUE 
} 
0

如果您沒有正確地生成線性同餘PRNG(僞隨機數生成器),您將始終獲得相同的值。 LCPRNG只是一個簡單的線性方程,定義爲X(n + 1)=(X(n)* A + B)%C,其中A,B和C是常數(並且X(0)是種子)。

調用使用相同的參數將設置X(0)相同的值...不是調用函數srand(srand()函數)將使用默認的X(0),每次...

一種方式來獲得一個「隨機」的種子是調用srand():

srand(time(NULL)); 
相關問題