Apache Commons logo Apache Commons RNG

Apache Commons RNG: Random Numbers Generators

Commons RNG provides implementations of pseudo-random numbers generators that are faster; of higher quality; and/or of a longer period than java.util.Random and java.util.SplittableRandom.

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> elements = new HashSet<>();
elements.add("Apache");
elements.add("Commons");
elements.add("RNG");

CollectionSampler<String> sampler = new CollectionSampler<>(RandomSource.MWC_256.create(),
                                                            elements);
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 = UnitSphereSampler.of(dimension, RandomSource.KISS.create());

double[] vector = sampler.sample();

Browse the Javadoc for more information.