mercredi 27 avril 2016

C++ and rand/srand behavior not performing as expected

I am using rand and srand from cstdlib and g++ as a compiler. I was playing around trying to generate some pseudo random numbers and I was getting some unexpected biased results. I was curious so I wrote a simple function. The expected behavior would be that a random number between 1 and 10 would be generated and printed out to screen a 100x's. The expected value of the average should be 5. However, when I run this function it will a generate a single random number between 1 and 10 and print it 100x's with the average being equal to the random number that was generated.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

float bs(){
        float random;
        srand(time(0));
        random = rand() % 10 + 1;

        return random;
}


int main(){

        float average;
        float random;

        for (int i = 1; i < 101; ++i)
        {
                random  += bs();
                cout << random << endl;
        }

        average = random/100;
        cout << average << endl;

        return 0;
}

If the initial return from bs = 7 it will stay 7 for the duration of the loop and each time bs() is called. The output will be 7 added to itself 100x's and the average will be equal to gasp 7. What is going on here?




Aucun commentaire:

Enregistrer un commentaire