Class RandomDataImpl
- java.lang.Object
-
- 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 theRandomData
interface using aRandomGenerator
instance to generate non-secure data and aSecureRandom
instance to provide data for thenextSecureXxx
methods. If noRandomGenerator
is provided in the constructor, the default is to use a generator based onRandom
. To plug in a different implementation, either implementRandomGenerator
directly or extendAbstractRandomGenerator
.Supports reseeding the underlying pseudo-random number generator (PRNG). The
SecurityProvider
andAlgorithm
used by theSecureRandom
instance can also be reset.For details on the default PRNGs, see
Random
andSecureRandom
.Usage Notes:
-
Instance variables are used to maintain
RandomGenerator
andSecureRandom
instances used in data generation. Therefore, to generate a random sequence of values or strings, you should use just oneRandomDataImpl
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 on first use. The same holds for the secure generator. If you provide aRandomGenerator
to the constructor, however, this generator is not reseeded by the constructor nor is it reseeded on first use. -
The
reSeed
andreSeedSecure
methods delegate to the corresponding methods on the underlyingRandomGenerator
andSecureRandom
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:
- $Revision: 1061496 $ $Date: 2011-01-20 21:32:16 +0100 (jeu. 20 janv. 2011) $
- See Also:
- Serialized Form
-
-
Constructor Summary
Constructors Constructor Description RandomDataImpl()
Construct a RandomDataImpl.RandomDataImpl(RandomGenerator rand)
Construct a RandomDataImpl using the suppliedRandomGenerator
as the source of (non-secure) random data.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description double
nextBeta(double alpha, double beta)
Generates a random value from theBeta Distribution
.int
nextBinomial(int numberOfTrials, double probabilityOfSuccess)
Generates a random value from theBinomial Distribution
.double
nextCauchy(double median, double scale)
Generates a random value from theCauchy Distribution
.double
nextChiSquare(double df)
Generates a random value from theChiSquare Distribution
.double
nextExponential(double mean)
Returns a random value from an Exponential distribution with the given mean.double
nextF(double numeratorDf, double denominatorDf)
Generates a random value from theF Distribution
.double
nextGamma(double shape, double scale)
Generates a random value from theGamma Distribution
.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 lengthlen
.int
nextHypergeometric(int populationSize, int numberOfSuccesses, int sampleSize)
Generates a random value from theHypergeometric Distribution
.int
nextInt(int lower, int upper)
Generate a random int value uniformly distributed betweenlower
andupper
, inclusive.double
nextInversionDeviate(ContinuousDistribution distribution)
Generate a random deviate from the given distribution using the inversion method.int
nextInversionDeviate(IntegerDistribution distribution)
Generate a random deviate from the given distribution using the inversion method.long
nextLong(long lower, long upper)
Generate a random long value uniformly distributed betweenlower
andupper
, inclusive.int
nextPascal(int r, double p)
Generates a random value from thePascal Distribution
.int[]
nextPermutation(int n, int k)
Generates an integer array of lengthk
whose entries are selected randomly, without repetition, from the integers0 through n-1
(inclusive).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 betweenlower
andupper
, inclusive.long
nextSecureLong(long lower, long upper)
Generate a random long value uniformly distributed betweenlower
andupper
, inclusive.double
nextT(double df)
Generates a random value from theT Distribution
.double
nextUniform(double lower, double upper)
Generates a uniformly distributed random value from the open interval (lower
,upper
) (i.e., endpoints excluded).double
nextWeibull(double shape, double scale)
Generates a random value from theWeibull Distribution
.int
nextZipf(int numberOfElements, double exponent)
Generates a random value from theZipf Distribution
.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.
-
-
-
Constructor Detail
-
RandomDataImpl
public RandomDataImpl()
Construct a RandomDataImpl.
-
RandomDataImpl
public RandomDataImpl(RandomGenerator rand)
Construct a RandomDataImpl using the suppliedRandomGenerator
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 lengthlen
.The generated string will be random, but not cryptographically secure. To generate cryptographically secure strings, use
nextSecureHexString
Preconditions:
len > 0
(otherwise an IllegalArgumentException is thrown.)
Algorithm Description: hex strings are generated using a 2-step process.
- len/2+1 binary bytes are generated using the underlying Random
- Each binary byte is translated into 2 hex digits
- Specified by:
nextHexString
in interfaceRandomData
- Parameters:
len
- the desired string length.- Returns:
- the random string.
- Throws:
NotStrictlyPositiveException
- iflen <= 0
.
-
nextInt
public int nextInt(int lower, int upper)
Generate a random int value uniformly distributed betweenlower
andupper
, inclusive.- Specified by:
nextInt
in interfaceRandomData
- Parameters:
lower
- the lower bound.upper
- the upper bound.- Returns:
- the random integer.
- Throws:
NumberIsTooLargeException
- iflower >= upper
.
-
nextLong
public long nextLong(long lower, long upper)
Generate a random long value uniformly distributed betweenlower
andupper
, inclusive.- Specified by:
nextLong
in interfaceRandomData
- Parameters:
lower
- the lower bound.upper
- the upper bound.- Returns:
- the random integer.
- Throws:
NumberIsTooLargeException
- iflower >= upper
.
-
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:
len > 0
(otherwise an IllegalArgumentException is thrown.)
Algorithm Description: hex strings are generated in 40-byte segments using a 3-step process.
-
20 random bytes are generated using the underlying
SecureRandom
. - SHA-1 hash is applied to yield a 20-byte binary digest.
- Each byte of the binary digest is converted to 2 hex digits.
- Specified by:
nextSecureHexString
in interfaceRandomData
- Parameters:
len
- the length of the generated string- Returns:
- the random string
- Throws:
NotStrictlyPositiveException
- iflen <= 0
.
-
nextSecureInt
public int nextSecureInt(int lower, int upper)
Generate a random int value uniformly distributed betweenlower
andupper
, inclusive. This algorithm uses a secure random number generator.- Specified by:
nextSecureInt
in interfaceRandomData
- Parameters:
lower
- the lower bound.upper
- the upper bound.- Returns:
- the random integer.
- Throws:
NumberIsTooLargeException
- iflower >= upper
.
-
nextSecureLong
public long nextSecureLong(long lower, long upper)
Generate a random long value uniformly distributed betweenlower
andupper
, inclusive. This algorithm uses a secure random number generator.- Specified by:
nextSecureLong
in interfaceRandomData
- Parameters:
lower
- the lower bound.upper
- the upper bound.- Returns:
- the random integer.
- Throws:
NumberIsTooLargeException
- iflower >= upper
.
-
nextPoisson
public long nextPoisson(double mean)
Generates a random value from the Poisson distribution with the given mean.Definition: Poisson Distribution
Preconditions:
- The specified mean must be positive (otherwise an IllegalArgumentException is thrown.)
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 interfaceRandomData
- Parameters:
mean
- mean of the Poisson distribution.- Returns:
- the random Poisson value.
- Throws:
NotStrictlyPositiveException
- ifmean <= 0
.
-
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 interfaceRandomData
- Parameters:
mu
- the mean of the distributionsigma
- the standard deviation of the distribution- Returns:
- the random Normal value
- Throws:
NotStrictlyPositiveException
- ifsigma <= 0
.
-
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 interfaceRandomData
- Parameters:
mean
- the mean of the distribution- Returns:
- the random Exponential value
- Throws:
NotStrictlyPositiveException
- ifmean <= 0
.
-
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
andupper - lower
are the location and scale parameters, respectively.Preconditions:
lower < upper
(otherwise an IllegalArgumentException is thrown.)
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 interfaceRandomData
- Parameters:
lower
- the lower bound.upper
- the upper bound.- Returns:
- a uniformly distributed random value from the interval (lower, upper)
- Throws:
NumberIsTooLargeException
- iflower >= upper
.
-
nextBeta
public double nextBeta(double alpha, double beta) throws MathException
Generates a random value from theBeta Distribution
. This implementation usesinversion
to generate random values.- Parameters:
alpha
- first distribution shape parameterbeta
- second distribution shape parameter- Returns:
- random value sampled from the beta(alpha, beta) distribution
- Throws:
MathException
- if an error occurs generating the random value- Since:
- 2.2
-
nextBinomial
public int nextBinomial(int numberOfTrials, double probabilityOfSuccess) throws MathException
Generates a random value from theBinomial Distribution
. This implementation usesinversion
to generate random values.- Parameters:
numberOfTrials
- number of trials of the Binomial distributionprobabilityOfSuccess
- probability of success of the Binomial distribution- Returns:
- random value sampled from the Binomial(numberOfTrials, probabilityOfSuccess) distribution
- Throws:
MathException
- if an error occurs generating the random value- Since:
- 2.2
-
nextCauchy
public double nextCauchy(double median, double scale) throws MathException
Generates a random value from theCauchy Distribution
. This implementation usesinversion
to generate random values.- Parameters:
median
- the median of the Cauchy distributionscale
- the scale parameter of the Cauchy distribution- Returns:
- random value sampled from the Cauchy(median, scale) distribution
- Throws:
MathException
- if an error occurs generating the random value- Since:
- 2.2
-
nextChiSquare
public double nextChiSquare(double df) throws MathException
Generates a random value from theChiSquare Distribution
. This implementation usesinversion
to generate random values.- Parameters:
df
- the degrees of freedom of the ChiSquare distribution- Returns:
- random value sampled from the ChiSquare(df) distribution
- Throws:
MathException
- if an error occurs generating the random value- Since:
- 2.2
-
nextF
public double nextF(double numeratorDf, double denominatorDf) throws MathException
Generates a random value from theF Distribution
. This implementation usesinversion
to generate random values.- Parameters:
numeratorDf
- the numerator degrees of freedom of the F distributiondenominatorDf
- the denominator degrees of freedom of the F distribution- Returns:
- random value sampled from the F(numeratorDf, denominatorDf) distribution
- Throws:
MathException
- if an error occurs generating the random value- Since:
- 2.2
-
nextGamma
public double nextGamma(double shape, double scale) throws MathException
Generates a random value from theGamma Distribution
. This implementation usesinversion
to generate random values.- Parameters:
shape
- the median of the Gamma distributionscale
- the scale parameter of the Gamma distribution- Returns:
- random value sampled from the Gamma(shape, scale) distribution
- Throws:
MathException
- if an error occurs generating the random value- Since:
- 2.2
-
nextHypergeometric
public int nextHypergeometric(int populationSize, int numberOfSuccesses, int sampleSize) throws MathException
Generates a random value from theHypergeometric Distribution
. This implementation usesinversion
to generate random values.- Parameters:
populationSize
- the population size of the Hypergeometric distributionnumberOfSuccesses
- number of successes in the population of the Hypergeometric distributionsampleSize
- the sample size of the Hypergeometric distribution- Returns:
- random value sampled from the Hypergeometric(numberOfSuccesses, sampleSize) distribution
- Throws:
MathException
- if an error occurs generating the random value- Since:
- 2.2
-
nextPascal
public int nextPascal(int r, double p) throws MathException
Generates a random value from thePascal Distribution
. This implementation usesinversion
to generate random values.- Parameters:
r
- the number of successes of the Pascal distributionp
- the probability of success of the Pascal distribution- Returns:
- random value sampled from the Pascal(r, p) distribution
- Throws:
MathException
- if an error occurs generating the random value- Since:
- 2.2
-
nextT
public double nextT(double df) throws MathException
Generates a random value from theT Distribution
. This implementation usesinversion
to generate random values.- Parameters:
df
- the degrees of freedom of the T distribution- Returns:
- random value from the T(df) distribution
- Throws:
MathException
- if an error occurs generating the random value- Since:
- 2.2
-
nextWeibull
public double nextWeibull(double shape, double scale) throws MathException
Generates a random value from theWeibull Distribution
. This implementation usesinversion
to generate random values.- Parameters:
shape
- the shape parameter of the Weibull distributionscale
- the scale parameter of the Weibull distribution- Returns:
- random value sampled from the Weibull(shape, size) distribution
- Throws:
MathException
- if an error occurs generating the random value- Since:
- 2.2
-
nextZipf
public int nextZipf(int numberOfElements, double exponent) throws MathException
Generates a random value from theZipf Distribution
. This implementation usesinversion
to generate random values.- Parameters:
numberOfElements
- the number of elements of the ZipfDistributionexponent
- the exponent of the ZipfDistribution- Returns:
- random value sampled from the Zipf(numberOfElements, exponent) distribution
- Throws:
MathException
- if an error occurs generating the random value- Since:
- 2.2
-
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 algorithmprovider
- the name of the provider- Throws:
java.security.NoSuchAlgorithmException
- if the specified algorithm is not availablejava.security.NoSuchProviderException
- if the specified provider is not installed
-
nextPermutation
public int[] nextPermutation(int n, int k)
Generates an integer array of lengthk
whose entries are selected randomly, without repetition, from the integers0 through n-1
(inclusive).Generated arrays represent permutations of
n
takenk
at a time.Preconditions:
-
k <= n
-
n > 0
Uses a 2-cycle permutation shuffle. The shuffling process is described here.
- Specified by:
nextPermutation
in interfaceRandomData
- Parameters:
n
- domain of the permutation (must be positive)k
- size of the permutation (must satisfy 0 < k <= n).- Returns:
- the random permutation as an int array
- Throws:
NumberIsTooLargeException
- ifk > n
.NotStrictlyPositiveException
- ifk <= 0
.
-
-
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 ofc.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 interfaceRandomData
- Parameters:
c
- Collection to sample from.k
- sample size.- Returns:
- the random sample.
- Throws:
NumberIsTooLargeException
- ifk > c.size()
.NotStrictlyPositiveException
- ifk <= 0
.
-
nextInversionDeviate
public double nextInversionDeviate(ContinuousDistribution distribution) throws MathException
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
- Throws:
MathException
- if an error occurs computing the inverse cumulative distribution function- Since:
- 2.2
-
nextInversionDeviate
public int nextInversionDeviate(IntegerDistribution distribution) throws MathException
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
- Throws:
MathException
- if an error occurs computing the inverse cumulative distribution function- Since:
- 2.2
-
-