vendredi 14 août 2015

What is wrong with my Java Poisson random numbers generator?

My Java Poisson random numbers generator is just the translation in Java of the second one on Wikipedia. Here is the code :

private static int poisson(double lambda){
        double lambda_left = lambda;
        double p = 1;
        int k = 1;
        int step = 500;
        do{
                p *= Math.random();
                k ++;
                if (p < Math.E && lambda_left > 0)
                        if (lambda_left > step)
                        {
                                p *= Math.exp(step);
                                lambda_left -= step;
                        }
                        else
                        {
                                p *= Math.exp(lambda_left);
                                lambda_left = -1;
                        }
        }
        while (p > 1.);
        return k;
}

But then when I test it, it is biased :

public static void main(String[] args){
        for(int times = 0; times<4; times++){
                int n = 10000;
                double sum = 0;
                for(int i = 0; i<n; i++)
                        sum += poisson(10);
                System.out.println(sum/n);
        }
}

Output :

11.9933
11.99
11.9692
11.9763

By Central limit theorem, those means should be very close to 10 with very high probability (samples of size 10000 !), they should not be about 12 with high probability.. So what is wrong in my Java Poisson random numbers generator ?




Aucun commentaire:

Enregistrer un commentaire