samedi 21 février 2015

C++ Random Number Check for Very Small Probabilities

I have a very small probability of an event occurring (of order 1e-5) and am trying to use a uniform random number to test for success. As the probability drops to around 1e-4 the fraction of successes no longer matches the probability in the test code below.


How can I get an accurate check for success with such small probabilities? I tried using other random number generators but all the suggestions I found were for C++11 which I am not using. Many thanks in advance!



#include <cstlib>
#include <iostream>
#include <cmath>

double Prob, rand_num, frac_success;
int num_success, num_tries;

Prob = 1e-4;
num_tries = 1e8;
num_success = 0;

for (int i=0; i<num_tries; i++) {
rand_num = (double) rand() / RAND_MAX; // random number between 0 and 1

if (rand_num < Prob) {
num_success ++; // Record success
}
}
frac_success = double(num_success) / double(num_tries);

cout << Prob << endl << frac_success << endl;


The fraction of successes is roughly equal to Prob when Prob = 1e-3, but for Prob = 1e-4 it is always greater than 1.2e-4. The discrepancy gets worse with lower probabilities, and does not seem to be fixed by increasing the number of tries.





Aucun commentaire:

Enregistrer un commentaire