samedi 10 juillet 2021

Similar random number generation in python and c++ but getting different output

I have two functions, in c++ and python, that determine how many times an event with a certain probability will occur over a number of rolls.

Python version:

def get_loot(rolls):
    drops = 0

    for i in range(rolls):
        # getting a random float with 2 decimal places
        roll = random.randint(0, 10000) / 100
        if roll < 0.04:
            drops += 1

    return drops

for i in range(0, 10):
    print(get_loot(1000000))

Python output:

371
396
392
406
384
392
380
411
393
434

c++ version:

int get_drops(int rolls){
    int drops = 0;
    for(int i = 0; i < rolls; i++){
        // getting a random float with 2 decimal places
        float roll = (rand() % 10000)/100.0f;
        if (roll < 0.04){
            drops++;
        }
    }
    return drops;
}

int main()
{
    srand(time(NULL));
    for (int i = 0; i <= 10; i++){
        cout << get_drops(1000000) << "\n";
    }
}

c++ output:

602
626
579
589
567
620
603
608
594
610
626

The cood looks identical (at least to me). Both functions simulate an occurence of an event with a probablilty of 0.04 over 1,000,000 rolls. However the output of the python version is about 30% lower than that of the c++ version. How are these two versions different and why do they have different outputs?




Aucun commentaire:

Enregistrer un commentaire