Apache Commons logo Apache Commons RNG

Apache Commons RNG: Random Numbers Generators

Commons RNG provides implementations of pseudo-random numbers generators that are either faster or of higher quality (and sometimes both) than java.util.Random.

The "sampling" module contains classes to generate samples that follow the statistics of a given distribution.

Example:

import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.sampling.distribution.ContinuousSampler;
import org.apache.commons.rng.sampling.distribution.ZigguratSampler.Gaussian;

public class NormalDeviates {
    private final ContinuousSampler normalizedGaussian;

    public NormalDeviates(UniformRandomProvider rng) {
        normalizedGaussian = ZigguratSampler.Gaussian.of(rng);
    }

    public double sample(double mean,
                         double sigma) {
        return mean + sigma * normalizedGaussian.sample();
    }
}

Utilities are provided to sample from generic collections.

Example:

import org.apache.commons.rng.UniformRandomProvider;
import java.util.HashSet;
import org.apache.commons.rng.sampling.CollectionSampler;

HashSet<String> list = new HashSet<String>();
list.add("Apache");
list.add("Commons");
list.add("RNG");

CollectionSampler<String> sampler = new CollectionSampler<String>(RandomSource.MWC_256.create(),
                                                                  list);
String word = sampler.sample();

The module also contains classes to generate coordinate samples from geometric shapes such as inside a ball, box or triangle or on the surface of a sphere.

Example:

import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.sampling.UnitSphereSampler;

int dimension = 3;
UnitSphereSampler sampler = new UnitSphereSampler(dimension, RandomSource.KISS.create());

double[] vector = sampler.sample();

Browse the Javadoc for more information.