vendredi 24 mars 2017

c++ rand() - possible side-effect of If-statement

I am new to c++ and require your help regarding the rand() command in the following function:

// select_action function
void Agent::select_action(){

    // generate random number between 1 and 100
    int random_number = rand() % 100;

    cout << random_number << endl;

    if(random_number < (100*epsilon)){
        // select random action
        select_random_action();
        // cout << "pick random action" << endl;
    } else{
        // select action according to policy
        select_policy_action();
        // cout << "pick policy action" << endl;
    }
}

The above function has to select different functions dependent on the value of random_number. random_number is generated with the rand() command; I declared srand(time(NULL)) at the start of the main function.

Problem: the value of random_number is not random. If I loop over the above function the value is often the same or sequences through 2-5 different values. If, however, I declare a variable "a" and assign it similarly as random_variable, "a" does generate random values. Heuristically I found out that the first condition in the if statement messes up the randomness of the variable.

Does anyone know how to solve this problem?

Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire