org.apache.commons.math.random
Class RandomDataImpl

java.lang.Object
  extended by org.apache.commons.math.random.RandomDataImpl
All Implemented Interfaces:
java.io.Serializable, RandomData

public class RandomDataImpl
extends java.lang.Object
implements RandomData, java.io.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 generator based on Random. 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:

Version:
$Revision: 615734 $ $Date: 2008-01-27 23:10:03 -0700 (Sun, 27 Jan 2008) $
See Also:
Serialized Form

Field Summary
private  RandomGenerator rand
          underlying random number generator
private  java.security.SecureRandom secRand
          underlying secure random number generator
private static long serialVersionUID
          Serializable version identifier
 
Constructor Summary
RandomDataImpl()
          Construct a RandomDataImpl.
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  java.security.SecureRandom getSecRan()
          Returns the SecureRandom used to generate secure random data.
 double nextExponential(double mean)
          Returns a random value from an Exponential distribution with the given mean.
 double nextGaussian(double mu, double sigma)
          Generate a random value from a Normal (a.k.a.
 java.lang.String nextHexString(int len)
          Generates a random string of hex characters of length len.
 int nextInt(int lower, int upper)
          Generate a random int value uniformly distributed between lower and upper, inclusive.
 long nextLong(long lower, long upper)
          Generate a random long value uniformly distributed between lower and upper, inclusive.
 int[] nextPermutation(int n, int k)
          Uses a 2-cycle permutation shuffle to generate a random permutation.
 long nextPoisson(double mean)
          Generates a random value from the Poisson distribution with the given mean.
 java.lang.Object[] nextSample(java.util.Collection c, int k)
          Uses a 2-cycle permutation shuffle to generate a random permutation.
 java.lang.String nextSecureHexString(int len)
          Generates a random string of hex characters from a secure random sequence.
 int nextSecureInt(int lower, int upper)
          Generate a random int value uniformly distributed between lower and upper, inclusive.
 long nextSecureLong(long lower, long upper)
          Generate a random long value uniformly distributed between lower and upper, inclusive.
 double nextUniform(double lower, double upper)
          Generates a uniformly distributed random value from the open interval (lower,upper) (i.e., endpoints excluded).
 void reSeed()
          Reseeds the random number generator with the current time in milliseconds.
 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(java.lang.String algorithm, java.lang.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

rand

private RandomGenerator rand
underlying random number generator


secRand

private java.security.SecureRandom secRand
underlying secure random number generator

Constructor Detail

RandomDataImpl

public RandomDataImpl()
Construct a RandomDataImpl.


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
Since:
1.1
Method Detail

nextHexString

public java.lang.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 nextSecureHexString

Preconditions:

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.

nextInt

public int nextInt(int lower,
                   int upper)
Generate a random int value uniformly distributed between lower and upper, inclusive.

Specified by:
nextInt in interface RandomData
Parameters:
lower - the lower bound.
upper - the upper bound.
Returns:
the random integer.

nextLong

public long nextLong(long lower,
                     long upper)
Generate a random long value uniformly distributed between lower and upper, inclusive.

Specified by:
nextLong in interface RandomData
Parameters:
lower - the lower bound.
upper - the upper bound.
Returns:
the random integer.

nextSecureHexString

public java.lang.String nextSecureHexString(int len)
Generates a random string of hex characters from a secure random sequence.

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

Preconditions:

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 generated string
Returns:
the random string

nextSecureInt

public int nextSecureInt(int lower,
                         int upper)
Generate a random int value uniformly distributed between lower and upper, inclusive. This algorithm uses a secure random number generator.

Specified by:
nextSecureInt in interface RandomData
Parameters:
lower - the lower bound.
upper - the upper bound.
Returns:
the random integer.

nextSecureLong

public long nextSecureLong(long lower,
                           long upper)
Generate a random long value uniformly distributed between lower and upper, inclusive. This algorithm uses a secure random number generator.

Specified by:
nextSecureLong in interface RandomData
Parameters:
lower - the lower bound.
upper - the upper bound.
Returns:
the random integer.

nextPoisson

public long nextPoisson(double mean)
Generates a random value from the Poisson distribution with the given mean.

Definition: Poisson Distribution

Preconditions:

Algorithm Description: Uses simulation of a Poisson process using Uniform deviates, as described here.

The Poisson process (and hence value returned) is bounded by 1000 * mean.

Specified by:
nextPoisson in interface RandomData
Parameters:
mean - mean of the Poisson distribution.
Returns:
the random Poisson value.

nextGaussian

public double nextGaussian(double mu,
                           double sigma)
Generate a random value from a Normal (a.k.a. Gaussian) distribution with the given mean, mu and the given standard deviation, sigma.

Specified by:
nextGaussian in interface RandomData
Parameters:
mu - the mean of the distribution
sigma - the standard deviation of the distribution
Returns:
the random Normal value

nextExponential

public double nextExponential(double mean)
Returns a random value from an Exponential distribution with the given mean.

Algorithm Description: Uses the Inversion Method to generate exponentially distributed random values from uniform deviates.

Specified by:
nextExponential in interface RandomData
Parameters:
mean - the mean of the distribution
Returns:
the random Exponential value

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.

Preconditions:

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 lower bound.
upper - the upper bound.
Returns:
a uniformly distributed random value from the interval (lower, upper)

getRan

private RandomGenerator getRan()
Returns the RandomGenerator used to generate non-secure random data.

Creates and initializes a default generator if null.

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

getSecRan

private java.security.SecureRandom getSecRan()
Returns the SecureRandom used to generate secure random data.

Creates and initializes if null.

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 the current time in milliseconds.


setSecureAlgorithm

public void setSecureAlgorithm(java.lang.String algorithm,
                               java.lang.String provider)
                        throws java.security.NoSuchAlgorithmException,
                               java.security.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:
java.security.NoSuchAlgorithmException - if the specified algorithm is not available
java.security.NoSuchProviderException - if the specified provider is not installed

nextPermutation

public int[] nextPermutation(int n,
                             int k)
Uses a 2-cycle permutation shuffle to generate a random permutation. The shuffling process is described here.

Specified by:
nextPermutation in interface RandomData
Parameters:
n - the population size.
k - the number to choose.
Returns:
the random permutation.

nextSample

public java.lang.Object[] nextSample(java.util.Collection c,
                                     int k)
Uses a 2-cycle permutation shuffle to generate a random permutation. 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 - Collection to sample from.
k - sample size.
Returns:
the random sample.

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