mercredi 30 septembre 2020

How do I unit test my random generator function?

I wrote the following 4-liner in C as a helper function, but I now find it useful beyond what I had anticipated and would like to cover it in my tests.

double random_double_in_range(double min, double max) {
    // This cannot overflow, no matter the values of min, max and x.
    // It will return an uniformly distributed double
    // between min and max, inclusive.
    int n = rand();
    if (n==0) return min;
    double x = (double) n;
    return x * (max / RAND_MAX - min / RAND_MAX + min / x);
}

I wrote the comment and believe it to be true, but how can I really without tests?

I can easily test that the returned value is within the bounds, but how can I write a test that determines whether it is actually uniformly distributed? If I simply run it one million times and check that it fits a uniform distribution within some tolerance, eventually it will exceed that tolerance and fail spuriously.

I know that probably there exist libraries that do this already; this is more of a personal exercise (how do they do their testing?)




Aucun commentaire:

Enregistrer un commentaire