The Java Random class makes available a few different pseudo-random distribution from which we can extract variables and play with them. Here we are going to use values returned by nextDouble(), method that returns a value picked up from a uniform distribution between 0.0 and 1.0, and nextGaussian(), that refers to a Gaussian ("normal") distribution with mean 0 and standard deviation 1.

To spice things a bit, we will also manipulate the gaussian values to get a square gaussian distribution.

The mean for the variables generated from Random.nextDouble() should tend to 0.5, as we should find out running a few times this function with increasing values of "n":

double expectU(int n) { double sum =0; for(int i =0; i < n; ++i) sum += generator.nextDouble(); return sum/n; }Doesn't change much for Random.nextGaussian(), but that it should tend to a mean of 0.0:

double expectG(int n) { double sum =0; for(int i =0; i < n; ++i) sum += generator.nextGaussian(); return sum/n; }A bit more interesting the square gaussian case, since we provide an adaptor from Random.nextGaussian():

double squareGaussian() { return Math.pow(generator.nextGaussian(), 2); } double expectSG(int n) { double sum =0; for(int i =0; i < n; ++i) sum += squareGaussian(); return sum/n; }In this last test we should see how, for increasing values of n, the resulting expected mean value should tend to 1.0.

## No comments:

## Post a Comment