## org.apache.commons.math3.random
Class RandomDataImpl

    java.lang.Object
      org.apache.commons.math3.random.RandomDataImpl

All Implemented Interfaces:
  Serializable, RandomData

    public class RandomDataImpl

extends Object
implements RandomData, Serializable

Implements the `RandomData` interface using a `RandomGenerator` instance to generate non-secure data and a `SecureRandom` instance to provide data for the `nextSecureXxx` methods. If no `RandomGenerator` is provided in the constructor, the default is to use a `Well19937c` generator. To plug in a different implementation, either implement `RandomGenerator` directly or extend `AbstractRandomGenerator`.

Supports reseeding the underlying pseudo-random number generator (PRNG). The `SecurityProvider` and `Algorithm` used by the `SecureRandom` instance can also be reset.

For details on the default PRNGs, see `Random` and `SecureRandom`.

Usage Notes:

- Instance variables are used to maintain `RandomGenerator` and `SecureRandom` instances used in data generation. Therefore, to generate a random sequence of values or strings, you should use just one `RandomDataImpl` instance repeatedly.
- The "secure" methods are *much* slower. These should be used only when a cryptographically secure random sequence is required. A secure random sequence is a sequence of pseudo-random values which, in addition to being well-dispersed (so no subsequence of values is an any more likely than other subsequence of the the same length), also has the additional property that knowledge of values generated up to any point in the sequence does not make it any easier to predict subsequent values.
- When a new `RandomDataImpl` is created, the underlying random number generators are not initialized. If you do not explicitly seed the default non-secure generator, it is seeded with the current time in milliseconds plus the system identity hash code on first use. The same holds for the secure generator. If you provide a `RandomGenerator` to the constructor, however, this generator is not reseeded by the constructor nor is it reseeded on first use.
- The `reSeed` and `reSeedSecure` methods delegate to the corresponding methods on the underlying `RandomGenerator` and `SecureRandom` instances. Therefore, `reSeed(long)` fully resets the initial state of the non-secure random number generator (so that reseeding with a specific value always results in the same subsequent random sequence); whereas reSeedSecure(long) does not reinitialize the secure random number generator (so secure sequences started with calls to reseedSecure(long) won't be identical).
- This implementation is not synchronized.

Version:
  $Id: RandomDataImpl.java 1296517 2012-03-02 23:55:08Z sebb $
See Also:
  Serialized Form

Field Summary
`private static double[]` `EXPONENTIAL_SA_QI` Used when generating Exponential samples.
`private RandomGenerator` `rand` underlying random number generator
`private SecureRandom` `secRand` underlying secure random number generator
`private static long` `serialVersionUID` Serializable version identifier

Constructor Summary
`RandomDataImpl()` Construct a RandomDataImpl, using a default random generator as the source of randomness.
`RandomDataImpl(RandomGenerator rand)` Construct a RandomDataImpl using the supplied `RandomGenerator` as the source of (non-secure) random data.

Method Summary
`private int[]` `getNatural(int n)` Returns an array representing n.
`private RandomGenerator` `getRan()` Returns the RandomGenerator used to generate non-secure random data.
`private SecureRandom` `getSecRan()` Returns the SecureRandom used to generate secure random data.
`private void` `initRan()` Sets the default generator to a `Well19937c` generator seeded with `System.currentTimeMillis() + System.identityHashCode(this))`.
`double` `nextBeta(double alpha, double beta)` Generates a random value from the `Beta Distribution`.
`int` `nextBinomial(int numberOfTrials, double probabilityOfSuccess)` Generates a random value from the `Binomial Distribution`.
`double` `nextCauchy(double median, double scale)` Generates a random value from the `Cauchy Distribution`.
`double` `nextChiSquare(double df)` Generates a random value from the `ChiSquare Distribution`.
`double` `nextExponential(double mean)` Generates a random value from the exponential distribution with specified mean.
`double` `nextF(double numeratorDf, double denominatorDf)` Generates a random value from the `F Distribution`.
`double` `nextGamma(double shape, double scale)` Generates a random value from the `Gamma Distribution`.
`double` `nextGaussian(double mu, double sigma)` Generates a random value from the Normal (or Gaussian) distribution with specified mean and standard deviation.
`String` `nextHexString(int len)` Generates a random string of hex characters of length `len`.
`int` `nextHypergeometric(int populationSize, int numberOfSuccesses, int sampleSize)` Generates a random value from the `Hypergeometric Distribution`.
`int` `nextInt(int lower, int upper)` Generates a uniformly distributed random integer between `lower` and `upper` (endpoints included).
`int` `nextInversionDeviate(IntegerDistribution distribution)` Generate a random deviate from the given distribution using the inversion method.
`double` `nextInversionDeviate(RealDistribution distribution)` Generate a random deviate from the given distribution using the inversion method.
`long` `nextLong(long lower, long upper)` Generates a uniformly distributed random long integer between `lower` and `upper` (endpoints included).
`int` `nextPascal(int r, double p)` Generates a random value from the `Pascal Distribution`.
`int[]` `nextPermutation(int n, int k)` Generates an integer array of length `k` whose entries are selected randomly, without repetition, from the integers `0, ..., n - 1` (inclusive).
`long` `nextPoisson(double mean)` Generates a random value from the Poisson distribution with the given mean.
`Object[]` `nextSample(Collection<?> c, int k)` Returns an array of `k` objects selected randomly from the Collection `c`.
`String` `nextSecureHexString(int len)` Generates a random string of hex characters from a secure random sequence.
`int` `nextSecureInt(int lower, int upper)` Generates a uniformly distributed random integer between `lower` and `upper` (endpoints included) from a secure random sequence.
`long` `nextSecureLong(long lower, long upper)` Generates a uniformly distributed random long integer between `lower` and `upper` (endpoints included) from a secure random sequence.
`double` `nextT(double df)` Generates a random value from the `T Distribution`.
`double` `nextUniform(double lower, double upper)` Generates a uniformly distributed random value from the open interval `(lower, upper)` (i.e., endpoints excluded).
`double` `nextUniform(double lower, double upper, boolean lowerInclusive)` Generates a uniformly distributed random value from the interval `(lower, upper)` or the interval `[lower, upper)`.
`double` `nextWeibull(double shape, double scale)` Generates a random value from the `Weibull Distribution`.
`int` `nextZipf(int numberOfElements, double exponent)` Generates a random value from the `Zipf Distribution`.
`void` `reSeed()` Reseeds the random number generator with `System.currentTimeMillis() + System.identityHashCode(this))`.
`void` `reSeed(long seed)` Reseeds the random number generator with the supplied seed.
`void` `reSeedSecure()` Reseeds the secure random number generator with the current time in milliseconds.
`void` `reSeedSecure(long seed)` Reseeds the secure random number generator with the supplied seed.
`void` `setSecureAlgorithm(String algorithm, String provider)` Sets the PRNG algorithm for the underlying SecureRandom instance using the Security Provider API.
`private void` `shuffle(int[] list, int end)` Uses a 2-cycle permutation shuffle to randomly re-order the last elements of list.

Methods inherited from class java.lang.Object
`clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

Field Detail

### serialVersionUID

    private static final long serialVersionUID

  Serializable version identifier

  See Also:
    Constant Field Values

### EXPONENTIAL_SA_QI

    private static final double[] EXPONENTIAL_SA_QI

  Used when generating Exponential samples. Table containing the constants q_i = sum_{j=1}^i (ln 2)^j/j! = ln 2 + (ln 2)^2/2 + ... + (ln 2)^i/i! until the largest representable fraction below 1 is exceeded. Note that 1 = 2 - 1 = exp(ln 2) - 1 = sum_{n=1}^infty (ln 2)^n / n! thus q_i -> 1 as i -> infty, so the higher i, the closer to one we get (the series is not alternating). By trying, n = 16 in Java is enough to reach 1.0.

### rand

    private RandomGenerator rand

  underlying random number generator

### secRand

    private SecureRandom secRand

  underlying secure random number generator

Constructor Detail

### RandomDataImpl

    public RandomDataImpl()

  Construct a RandomDataImpl, using a default random generator as the source of randomness.

  The default generator is a `Well19937c` seeded with `System.currentTimeMillis() + System.identityHashCode(this))`. The generator is initialized and seeded on first use.

### RandomDataImpl

    public RandomDataImpl(RandomGenerator rand)

  Construct a RandomDataImpl using the supplied `RandomGenerator` as the source of (non-secure) random data.

  Parameters:
    `rand` - the source of (non-secure) random data (may be null, resulting in the default generator)
  Since:
    1.1

Method Detail

### nextHexString

    public String nextHexString(int len)

  Generates a random string of hex characters of length `len`.

  The generated string will be random, but not cryptographically secure. To generate cryptographically secure strings, use `RandomData.nextSecureHexString(int)`.

  Algorithm Description: hex strings are generated using a 2-step process.

  1. `len / 2 + 1` binary bytes are generated using the underlying Random
  2. Each binary byte is translated into 2 hex digits

  Specified by:
    `nextHexString` in interface `RandomData`
  Parameters:
    `len` - the desired string length.
  Returns:
    the random string.
  Throws:
    `NotStrictlyPositiveException` - if `len <= 0`.

### nextInt

    public int nextInt(int lower,
                       int upper)

  Generates a uniformly distributed random integer between `lower` and `upper` (endpoints included).

  The generated integer will be random, but not cryptographically secure. To generate cryptographically secure integer sequences, use `RandomData.nextSecureInt(int, int)`.

  Specified by:
    `nextInt` in interface `RandomData`
  Parameters:
    `lower` - lower bound for generated integer
    `upper` - upper bound for generated integer
  Returns:
    a random integer greater than or equal to `lower` and less than or equal to `upper`

### nextLong

    public long nextLong(long lower,
                         long upper)

  Generates a uniformly distributed random long integer between `lower` and `upper` (endpoints included).

  The generated long integer values will be random, but not cryptographically secure. To generate cryptographically secure sequences of longs, use `RandomData.nextSecureLong(long, long)`.

  Specified by:
    `nextLong` in interface `RandomData`
  Parameters:
    `lower` - lower bound for generated long integer
    `upper` - upper bound for generated long integer
  Returns:
    a random long integer greater than or equal to `lower` and less than or equal to `upper`

### nextSecureHexString

    public String nextSecureHexString(int len)

  Generates a random string of hex characters from a secure random sequence.

  If cryptographic security is not required, use `RandomData.nextHexString(int)`.

  Algorithm Description: hex strings are generated in 40-byte segments using a 3-step process.

  1. 20 random bytes are generated using the underlying `SecureRandom`.
  2. SHA-1 hash is applied to yield a 20-byte binary digest.
  3. Each byte of the binary digest is converted to 2 hex digits.

  Specified by:
    `nextSecureHexString` in interface `RandomData`
  Parameters:
    `len` - the length of the string to be generated
  Returns:
    a random string of hex characters of length `len`

### nextSecureInt

    public int nextSecureInt(int lower,
                             int upper)

  Generates a uniformly distributed random integer between `lower` and `upper` (endpoints included) from a secure random sequence.

  Sequences of integers generated using this method will be cryptographically secure. If cryptographic security is not required, `RandomData.nextInt(int, int)` should be used instead of this method.

  Definition: Secure Random Sequence

  Specified by:
    `nextSecureInt` in interface `RandomData`
  Parameters:
    `lower` - lower bound for generated integer
    `upper` - upper bound for generated integer
  Returns:
    a random integer greater than or equal to `lower` and less than or equal to `upper`.

### nextSecureLong

    public long nextSecureLong(long lower,
                               long upper)

  Generates a uniformly distributed random long integer between `lower` and `upper` (endpoints included) from a secure random sequence.

  Sequences of long values generated using this method will be cryptographically secure. If cryptographic security is not required, `RandomData.nextLong(long, long)` should be used instead of this method.

  Definition: Secure Random Sequence

  Specified by:
    `nextSecureLong` in interface `RandomData`
  Parameters:
    `lower` - lower bound for generated integer
    `upper` - upper bound for generated integer
  Returns:
    a random long integer greater than or equal to `lower` and less than or equal to `upper`.

### nextPoisson

    public long nextPoisson(double mean)

  Generates a random value from the Poisson distribution with the given mean.

  Definition: Poisson Distribution

  Algorithm Description:

  - For small means, uses simulation of a Poisson process using Uniform deviates, as described here. The Poisson process (and hence value returned) is bounded by 1000 * mean.
  - For large means, uses the rejection algorithm described in
    Devroye, Luc. (1981).The Computer Generation of Poisson Random Variables Computing vol. 26 pp. 197-207.

  Specified by:
    `nextPoisson` in interface `RandomData`
  Parameters:
    `mean` - the mean of the Poisson distribution
  Returns:
    a random value following the specified Poisson distribution

### nextGaussian

    public double nextGaussian(double mu,
                               double sigma)

  Generates a random value from the Normal (or Gaussian) distribution with specified mean and standard deviation.

  Definition: Normal Distribution

  Specified by:
    `nextGaussian` in interface `RandomData`
  Parameters:
    `mu` - the mean of the distribution
    `sigma` - the standard deviation of the distribution
  Returns:
    a random value following the specified Gaussian distribution

### nextExponential

    public double nextExponential(double mean)

  Generates a random value from the exponential distribution with specified mean.

  Definition: Exponential Distribution

  Algorithm Description: Uses the Algorithm SA (Ahrens) from p. 876 in: [1]: Ahrens, J. H. and Dieter, U. (1972). Computer methods for sampling from the exponential and normal distributions. Communications of the ACM, 15, 873-882.

  Specified by:
    `nextExponential` in interface `RandomData`
  Parameters:
    `mean` - the mean of the distribution
  Returns:
    a random value following the specified exponential distribution

### nextUniform

    public double nextUniform(double lower,
                              double upper)

  Generates a uniformly distributed random value from the open interval `(lower, upper)` (i.e., endpoints excluded).

  Definition: Uniform Distribution `lower` and `upper - lower` are the location and scale parameters, respectively.

  Algorithm Description: scales the output of Random.nextDouble(), but rejects 0 values (i.e., will generate another random double if Random.nextDouble() returns 0). This is necessary to provide a symmetric output interval (both endpoints excluded).

  Specified by:
    `nextUniform` in interface `RandomData`
  Parameters:
    `lower` - the exclusive lower bound of the support
    `upper` - the exclusive upper bound of the support
  Returns:
    a uniformly distributed random value between lower and upper (exclusive)
  Throws:
    `MathIllegalArgumentException` - if one of the bounds is infinite or `NaN` or either bound is infinite or NaN

### nextUniform

    public double nextUniform(double lower,
                              double upper,
                              boolean lowerInclusive)

  Generates a uniformly distributed random value from the interval `(lower, upper)` or the interval `[lower, upper)`. The lower bound is thus optionally included, while the upper bound is always excluded.

  Definition: Uniform Distribution `lower` and `upper - lower` are the location and scale parameters, respectively.

  Algorithm Description: if the lower bound is excluded, scales the output of Random.nextDouble(), but rejects 0 values (i.e., will generate another random double if Random.nextDouble() returns 0). This is necessary to provide a symmetric output interval (both endpoints excluded).

  Specified by:
    `nextUniform` in interface `RandomData`
  Parameters:
    `lower` - the lower bound of the support
    `upper` - the exclusive upper bound of the support
    `lowerInclusive` - `true` if the lower bound is inclusive
  Returns:
    uniformly distributed random value in the `(lower, upper)` interval, if `lowerInclusive` is `false`, or in the `[lower, upper)` interval, if `lowerInclusive` is `true`
  Throws:
    `MathIllegalArgumentException` - if one of the bounds is infinite or `NaN`
  Since:
    3.0

### nextBeta

    public double nextBeta(double alpha,
                           double beta)

  Generates a random value from the `Beta Distribution`. This implementation uses `inversion` to generate random values.

  Parameters:
    `alpha` - first distribution shape parameter
    `beta` - second distribution shape parameter
  Returns:
    random value sampled from the beta(alpha, beta) distribution
  Since:
    2.2

### nextBinomial

    public int nextBinomial(int numberOfTrials,
                            double probabilityOfSuccess)

  Generates a random value from the `Binomial Distribution`. This implementation uses `inversion` to generate random values.

  Parameters:
    `numberOfTrials` - number of trials of the Binomial distribution
    `probabilityOfSuccess` - probability of success of the Binomial distribution
  Returns:
    random value sampled from the Binomial(numberOfTrials, probabilityOfSuccess) distribution
  Since:
    2.2

### nextCauchy

    public double nextCauchy(double median,
                             double scale)

  Generates a random value from the `Cauchy Distribution`. This implementation uses `inversion` to generate random values.

  Parameters:
    `median` - the median of the Cauchy distribution
    `scale` - the scale parameter of the Cauchy distribution
  Returns:
    random value sampled from the Cauchy(median, scale) distribution
  Since:
    2.2

### nextChiSquare

    public double nextChiSquare(double df)

  Generates a random value from the `ChiSquare Distribution`. This implementation uses `inversion` to generate random values.

  Parameters:
    `df` - the degrees of freedom of the ChiSquare distribution
  Returns:
    random value sampled from the ChiSquare(df) distribution
  Since:
    2.2

### nextF

    public double nextF(double numeratorDf,
                        double denominatorDf)

  Generates a random value from the `F Distribution`. This implementation uses `inversion` to generate random values.

  Parameters:
    `numeratorDf` - the numerator degrees of freedom of the F distribution
    `denominatorDf` - the denominator degrees of freedom of the F distribution
  Returns:
    random value sampled from the F(numeratorDf, denominatorDf) distribution
  Since:
    2.2

### nextGamma

    public double nextGamma(double shape,
                            double scale)

  Generates a random value from the `Gamma Distribution`.

  This implementation uses the following algorithms:

  For 0 < shape < 1:
  Ahrens, J. H. and Dieter, U., Computer methods for sampling from gamma, beta, Poisson and binomial distributions. Computing, 12, 223-246, 1974.

  For shape >= 1:
  Marsaglia and Tsang, A Simple Method for Generating Gamma Variables. ACM Transactions on Mathematical Software, Volume 26 Issue 3, September, 2000.

  Parameters:
    `shape` - the median of the Gamma distribution
    `scale` - the scale parameter of the Gamma distribution
  Returns:
    random value sampled from the Gamma(shape, scale) distribution
  Since:
    2.2

### nextHypergeometric

    public int nextHypergeometric(int populationSize,
                                  int numberOfSuccesses,
                                  int sampleSize)

  Generates a random value from the `Hypergeometric Distribution`. This implementation uses `inversion` to generate random values.

  Parameters:
    `populationSize` - the population size of the Hypergeometric distribution
    `numberOfSuccesses` - number of successes in the population of the Hypergeometric distribution
    `sampleSize` - the sample size of the Hypergeometric distribution
  Returns:
    random value sampled from the Hypergeometric(numberOfSuccesses, sampleSize) distribution
  Since:
    2.2

### nextPascal

    public int nextPascal(int r,
                          double p)

  Generates a random value from the `Pascal Distribution`. This implementation uses `inversion` to generate random values.

  Parameters:
    `r` - the number of successes of the Pascal distribution
    `p` - the probability of success of the Pascal distribution
  Returns:
    random value sampled from the Pascal(r, p) distribution
  Since:
    2.2

### nextT

    public double nextT(double df)

  Generates a random value from the `T Distribution`. This implementation uses `inversion` to generate random values.

  Parameters:
    `df` - the degrees of freedom of the T distribution
  Returns:
    random value from the T(df) distribution
  Since:
    2.2

### nextWeibull

    public double nextWeibull(double shape,
                              double scale)

  Generates a random value from the `Weibull Distribution`. This implementation uses `inversion` to generate random values.

  Parameters:
    `shape` - the shape parameter of the Weibull distribution
    `scale` - the scale parameter of the Weibull distribution
  Returns:
    random value sampled from the Weibull(shape, size) distribution
  Since:
    2.2

### nextZipf

    public int nextZipf(int numberOfElements,
                        double exponent)

  Generates a random value from the `Zipf Distribution`. This implementation uses `inversion` to generate random values.

  Parameters:
    `numberOfElements` - the number of elements of the ZipfDistribution
    `exponent` - the exponent of the ZipfDistribution
  Returns:
    random value sampled from the Zipf(numberOfElements, exponent) distribution
  Since:
    2.2

### getRan

    private RandomGenerator getRan()

  Returns the RandomGenerator used to generate non-secure random data.

  Creates and initializes a default generator if null. Uses a `Well19937c` generator with `System.currentTimeMillis() + System.identityHashCode(this))` as the default seed.

  Returns:
    the Random used to generate random data
  Since:
    1.1

### initRan

    private void initRan()

  Sets the default generator to a `Well19937c` generator seeded with `System.currentTimeMillis() + System.identityHashCode(this))`.

### getSecRan

    private SecureRandom getSecRan()

  Returns the SecureRandom used to generate secure random data.

  Creates and initializes if null. Uses `System.currentTimeMillis() + System.identityHashCode(this)` as the default seed.

  Returns:
    the SecureRandom used to generate secure random data

### reSeed

    public void reSeed(long seed)

  Reseeds the random number generator with the supplied seed.

  Will create and initialize if null.

  Parameters:
    `seed` - the seed value to use

### reSeedSecure

    public void reSeedSecure()

  Reseeds the secure random number generator with the current time in milliseconds.

  Will create and initialize if null.

### reSeedSecure

    public void reSeedSecure(long seed)

  Reseeds the secure random number generator with the supplied seed.

  Will create and initialize if null.

  Parameters:
    `seed` - the seed value to use

### reSeed

    public void reSeed()

  Reseeds the random number generator with `System.currentTimeMillis() + System.identityHashCode(this))`.

### setSecureAlgorithm

    public void setSecureAlgorithm(String algorithm,
                                   String provider)
                            throws NoSuchAlgorithmException,
                                   NoSuchProviderException

  Sets the PRNG algorithm for the underlying SecureRandom instance using the Security Provider API. The Security Provider API is defined in Java Cryptography Architecture API Specification & Reference.

  USAGE NOTE: This method carries significant overhead and may take several seconds to execute.

  Parameters:
    `algorithm` - the name of the PRNG algorithm
    `provider` - the name of the provider
  Throws:
    `NoSuchAlgorithmException` - if the specified algorithm is not available
    `NoSuchProviderException` - if the specified provider is not installed

### nextPermutation

    public int[] nextPermutation(int n,
                                 int k)

  Generates an integer array of length `k` whose entries are selected randomly, without repetition, from the integers `0, ..., n - 1` (inclusive).

  Generated arrays represent permutations of `n` taken `k` at a time.

  Uses a 2-cycle permutation shuffle. The shuffling process is described here.

  Specified by:
    `nextPermutation` in interface `RandomData`
  Parameters:
    `n` - the domain of the permutation
    `k` - the size of the permutation
  Returns:
    a random `k`-permutation of `n`, as an array of integers

### nextSample

    public Object[] nextSample(Collection<?> c,
                               int k)

  Returns an array of `k` objects selected randomly from the Collection `c`.

  Sampling from `c` is without replacement; but if `c` contains identical objects, the sample may include repeats. If all elements of `c` are distinct, the resulting object array represents a Simple Random Sample of size `k` from the elements of `c`.

  Algorithm Description: Uses a 2-cycle permutation shuffle to generate a random permutation of `c.size()` and then returns the elements whose indexes correspond to the elements of the generated permutation. This technique is described, and proven to generate random samples here

  Specified by:
    `nextSample` in interface `RandomData`
  Parameters:
    `c` - the collection to be sampled
    `k` - the size of the sample
  Returns:
    a random sample of `k` elements from `c`

### nextInversionDeviate

    public double nextInversionDeviate(RealDistribution distribution)

  Generate a random deviate from the given distribution using the inversion method.

  Parameters:
    `distribution` - Continuous distribution to generate a random value from
  Returns:
    a random value sampled from the given distribution
  Since:
    2.2

### nextInversionDeviate

    public int nextInversionDeviate(IntegerDistribution distribution)

  Generate a random deviate from the given distribution using the inversion method.

  Parameters:
    `distribution` - Integer distribution to generate a random value from
  Returns:
    a random value sampled from the given distribution
  Since:
    2.2

### shuffle

    private void shuffle(int[] list,
                         int end)

  Uses a 2-cycle permutation shuffle to randomly re-order the last elements of list.

  Parameters:
    `list` - list to be shuffled
    `end` - element past which shuffling begins

### getNatural

    private int[] getNatural(int n)

  Returns an array representing n.

  Parameters:
    `n` - the natural number to represent
  Returns:
    array with entries = elements of n

Copyright (c) 2003-2013 Apache Software Foundation