Class EnhancedRandom
- All Implemented Interfaces:
Externalizable,Serializable,RandomGenerator
- Direct Known Subclasses:
AceRandom,ArchivalWrapper,Bear32Random,Chill32Random,Chip32Random,Choo32Random,ChopRandom,Crand64Random,DistinctRandom,DistributedRandom,FlowRandom,FourWheelRandom,GoldenQuasiRandom,HornRandom,InterpolatedRandom,Jsf32Random,KnownSequenceRandom,LaserRandom,LCG64Random,LFSR64QuasiRandom,LowChangeQuasiRandom,MaceRandom,MizuchiRandom,Mx3Random,OrbitalRandom,PasarRandom,PcgRXSMXSRandom,PouchRandom,Respite32Random,ReverseWrapper,RomuTrioRandom,ScruffRandom,Sfc64Random,SoloRandom,StrangerRandom,Taxon32Random,ThrashRandom,ThrooshRandom,TraceRandom,TricycleRandom,TrimRandom,TupleQuasiRandom,VanDerCorputQuasiRandom,WhiskerRandom,Xoroshiro128StarStarRandom,Xoshiro128PlusPlusRandom,Xoshiro160RoadroxoRandom,Xoshiro256MX3Random,Xoshiro256StarStarRandom
Random, meant for random number generators
that would be too bare-bones with just Random's methods.- See Also:
-
Nested Class Summary
Nested classes/interfaces inherited from interface java.util.random.RandomGenerator
RandomGenerator.ArbitrarilyJumpableGenerator, RandomGenerator.JumpableGenerator, RandomGenerator.LeapableGenerator, RandomGenerator.SplittableGenerator, RandomGenerator.StreamableGenerator -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescription<T extends CharSequence & Appendable>
TappendSerialized(T sb) Serializes the current state of this EnhancedRandom and appends it to an Appendable CharSequence (such as a StringBuilder), which may be used bystringDeserialize(String)to load this state at another time.<T extends CharSequence & Appendable>
TappendSerialized(T sb, com.github.tommyettinger.digital.Base base) Serializes the current state of this EnhancedRandom and appends it to an Appendable CharSequence (such as a StringBuilder), which may be used bystringDeserialize(String)to load this state at another time.static booleanareEqual(EnhancedRandom left, EnhancedRandom right) Given two EnhancedRandom objects that could have the same or different classes, this returns true if they have the same class and same state, or false otherwise.abstract EnhancedRandomcopy()Creates a new EnhancedRandom with identical states to this one, so if the same EnhancedRandom methods are called on this object and its copy (in the same order), the same outputs will be produced.static longfixGamma(long gamma) Attempts to improve the quality of a "gamma" increment for an additive sequence.static longfixGamma(long gamma, int threshold) Attempts to improve the quality of a "gamma" increment for an additive sequence.Gets the guaranteed lowest number of different results this can return from its main generating method, which is normallynextLong()unlessmainlyGeneratesInt()returns true (then it isnextInt()).longgetSelectedState(int selection) Gets a selected state value from this EnhancedRandom.intGets the number of possible state variables that can be selected withgetSelectedState(int)orsetSelectedState(int, long).abstract StringgetTag()Gets the tag used to identify this type of EnhancedRandom, as a String.static BigIntegerlcm(BigInteger a, BigInteger b) Gets the least common multiple (lcm) of two BigInteger values, which here are usually returned bygetMinimumPeriod().booleanReturns true if this generator mainly operates via itsnextInt()method internally, which means itsnextLong()must generate twointvalues instead of naturally producing onelong.doublemaxDoubleOf(double innerBound, double outerBound, int trials) Returns the maximum result oftrialscalls tonextDouble(double, double)using the giveninnerBoundandouterBound.floatmaxFloatOf(float innerBound, float outerBound, int trials) Returns the maximum result oftrialscalls tonextFloat(float, float)using the giveninnerBoundandouterBound.intmaxIntOf(int innerBound, int outerBound, int trials) Returns the maximum result oftrialscalls tonextSignedInt(int, int)using the giveninnerBoundandouterBound.longmaxLongOf(long innerBound, long outerBound, int trials) Returns the maximum result oftrialscalls tonextSignedLong(long, long)using the giveninnerBoundandouterBound.doubleminDoubleOf(double innerBound, double outerBound, int trials) Returns the minimum result oftrialscalls tonextDouble(double, double)using the giveninnerBoundandouterBound.floatminFloatOf(float innerBound, float outerBound, int trials) Returns the minimum result oftrialscalls tonextFloat(float, float)using the giveninnerBoundandouterBound.intminIntOf(int innerBound, int outerBound, int trials) Returns the minimum result oftrialscalls tonextSignedInt(int, int)using the giveninnerBoundandouterBound.longminLongOf(long innerBound, long outerBound, int trials) Returns the minimum result oftrialscalls tonextSignedLong(long, long)using the giveninnerBoundandouterBound.intnext(int bits) Generates the next pseudorandom number with a specific maximum size in bits (not a max number).booleanReturns the next pseudorandom, uniformly distributedbooleanvalue from this random number generator's sequence.booleannextBoolean(float chance) Returns true if a random value between 0 and 1 is less than the specified value.voidnextBytes(byte[] bytes) Generates random bytes and places them into a user-supplied byte array.doubleReturns the next pseudorandom, uniformly distributeddoublevalue between0.0(inclusive) and1.0(exclusive) from this random number generator's sequence.doublenextDouble(double outerBound) Gets a pseudo-random double between 0 (inclusive) andouterBound(exclusive).doublenextDouble(double innerBound, double outerBound) Gets a pseudo-random double betweeninnerBound(inclusive) andouterBound(exclusive).doubleGets a random double between 0.0 and 1.0, exclusive at both ends; this method is also more uniform thannextDouble()if you use the bit-patterns of the returned doubles.doublenextExclusiveDouble(double outerBound) Just likenextDouble(double), but this is exclusive on both 0.0 andouterBound.doublenextExclusiveDouble(double innerBound, double outerBound) doubleGets a random double between 0.0 and 1.0, exclusive at both ends.floatGets a random float between 0.0 and 1.0, exclusive at both ends.floatnextExclusiveFloat(float outerBound) Just likenextFloat(float), but this is exclusive on both 0.0 andouterBound.floatnextExclusiveFloat(float innerBound, float outerBound) floatGets a random float between 0.0 and 1.0, exclusive at both ends.doubleGets a random double that may be positive or negative, but cannot be 0, and always has a magnitude less than 1.floatGets a random float that may be positive or negative, but cannot be 0, and always has a magnitude less than 1.doubleReturns a non-negativedoublevalue pseudorandomly chosen from an exponential distribution whose mean is 1.floatReturns the next pseudorandom, uniformly distributedfloatvalue between0.0(inclusive) and1.0(exclusive) from this random number generator's sequence.floatnextFloat(float outerBound) Gets a pseudo-random float between 0 (inclusive) andouterBound(exclusive).floatnextFloat(float innerBound, float outerBound) Gets a pseudo-random float betweeninnerBound(inclusive) andouterBound(exclusive).doubleReturns the next pseudorandom, Gaussian ("normally") distributeddoublevalue with mean0.0and standard deviation1.0from this random number generator's sequence.doublenextGaussian(double mean, double stddev) Returns the next pseudorandom, Gaussian ("normally") distributeddoublevalue with the specified mean and standard deviation from this random number generator's sequence.floatReturns the next pseudorandom, Gaussian ("normally") distributedfloatvalue with mean0.0and standard deviation1.0from this random number generator's sequence.floatnextGaussianFloat(float mean, float stddev) Returns the next pseudorandom, Gaussian ("normally") distributedfloatvalue with the specified mean and standard deviation from this random number generator's sequence.doubleThis is just likenextDouble(), returning a double between 0 and 1, except that it is inclusive on both 0.0 and 1.0.doublenextInclusiveDouble(double outerBound) Just likenextDouble(double), but this is inclusive on both 0.0 andouterBound.doublenextInclusiveDouble(double innerBound, double outerBound) floatThis is just likenextFloat(), returning a float between 0 and 1, except that it is inclusive on both 0.0 and 1.0.floatnextInclusiveFloat(float outerBound) Just likenextFloat(float), but this is inclusive on both 0.0 andouterBound.floatnextInclusiveFloat(float innerBound, float outerBound) intnextInt()Returns the next pseudorandom, uniformly distributedintvalue from this random number generator's sequence.intnextInt(int bound) Returns a pseudorandom, uniformly distributedintvalue between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.intnextInt(int innerBound, int outerBound) Returns a pseudorandom, uniformly distributedintvalue between the specifiedinnerBound(inclusive) and the specifiedouterBound(exclusive).abstract longnextLong()Returns the next pseudorandom, uniformly distributedlongvalue from this random number generator's sequence.longnextLong(long bound) Returns a pseudorandom, uniformly distributedlongvalue between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.longnextLong(long inner, long outer) Returns a pseudorandom, uniformly distributedlongvalue between the specifiedinnerBound(inclusive) and the specifiedouterBound(exclusive).intnextSign()Returns -1 or 1, randomly.intnextSignedInt(int outerBound) Returns a pseudorandom, uniformly distributedintvalue between an inner bound of 0 (inclusive) and the specifiedouterBound(exclusive).intnextSignedInt(int innerBound, int outerBound) Returns a pseudorandom, uniformly distributedintvalue between the specifiedinnerBound(inclusive) and the specifiedouterBound(exclusive).longnextSignedLong(long outerBound) Returns a pseudorandom, uniformly distributedlongvalue between an inner bound of 0 (inclusive) and the specifiedouterBound(exclusive).longnextSignedLong(long inner, long outer) Returns a pseudorandom, uniformly distributedlongvalue between the specifiedinnerBound(inclusive) and the specifiedouterBound(exclusive).floatReturns a triangularly distributed random number between -1.0 (exclusive) and 1.0 (exclusive), where values around zero are more likely.floatnextTriangular(float max) Returns a triangularly distributed random number between-max(exclusive) andmax(exclusive), where values around zero are more likely.floatnextTriangular(float min, float max) Returns a triangularly distributed random number betweenmin(inclusive) andmax(exclusive), where themodeargument defaults to the midpoint between the bounds, giving a symmetric distribution.floatnextTriangular(float min, float max, float mode) Returns a triangularly distributed random number betweenmin(inclusive) andmax(exclusive), where values aroundmodeare more likely.intnextUnsignedInt(int bound) Returns a pseudorandom, uniformly distributedintvalue between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.intOptional; moves the state to its previous value and returns the previous int that would have been produced bynextInt().longOptional; moves the state to its previous value and returns the previous long that would have been produced bynextLong().static doubleprobit(double d) A way of taking a double in the (0.0, 1.0) range and mapping it to a Gaussian or normal distribution, so high inputs correspond to high outputs, and similarly for the low range.<T> TrandomElement(List<T> list) Gets a randomly selected item from the given List, such as an ArrayList.<T> TrandomElement(T[] array) Gets a randomly-selected item from the given array, which must be non-null and non-emptystatic intrateGamma(long gamma) Attempts to check the quality of a "gamma" increment for an additive sequence.voidThe object implements the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays.static longUsesMath.random()to hastily put together a not-especially-uniformlongvalue, meant only to produce a seed when no seed was specified (the "I don't care" seed).abstract voidsetSeed(long seed) Sets the seed of this random number generator using a singlelongseed.voidsetSelectedState(int selection, long value) Sets a selected state value to the given longvalue.voidsetState(long state) Sets each state variable to the givenstate.voidsetState(long... states) Sets all state variables to alternating values chosen fromstates.voidsetState(long stateA, long stateB) Sets each state variable to eitherstateAorstateB, alternating.voidsetState(long stateA, long stateB, long stateC) Sets each state variable tostateA,stateB, orstateC, alternating.voidsetState(long stateA, long stateB, long stateC, long stateD) Sets each state variable tostateA,stateB,stateC, orstateD, alternating.voidsetState(long stateA, long stateB, long stateC, long stateD, long stateE) Sets each state variable tostateA,stateB,stateC,stateD, orstateE, alternating.voidsetState(long stateA, long stateB, long stateC, long stateD, long stateE, long stateF) Sets each state variable tostateA,stateB,stateC,stateD, orstateE, alternating.voidsetWith(EnhancedRandom other) Similar tocopy(), but fills this EnhancedRandom with the state of another EnhancedRandom, usually (but not necessarily) one of the same type.voidshuffle(boolean[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.voidshuffle(boolean[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.voidshuffle(byte[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.voidshuffle(byte[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.voidshuffle(char[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.voidshuffle(char[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.voidshuffle(double[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.voidshuffle(double[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.voidshuffle(float[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.voidshuffle(float[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.voidshuffle(int[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.voidshuffle(int[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.voidshuffle(long[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.voidshuffle(long[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.voidshuffle(short[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.voidshuffle(short[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.<T> voidShuffles the given List in-place pseudo-randomly, using this to determine how to shuffle.<T> voidShuffles a section of the given List in-place pseudo-randomly, using this to determine how to shuffle.<T> voidshuffle(T[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.<T> voidshuffle(T[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.longskip(long advance) Optional; advances or rolls back theEnhancedRandom' state without actually generating each number.stringDeserialize(String data) Given a String in the format produced bystringSerialize(), this will attempt to set this EnhancedRandom object to match the state in the serialized data.stringDeserialize(String data, com.github.tommyettinger.digital.Base base) Given a String in the format produced bystringSerialize(Base), and the sameBaseused by the serialization, this will attempt to set this EnhancedRandom object to match the state in the serialized data.Serializes the current state of this EnhancedRandom to a String that can be used bystringDeserialize(String)to load this state at another time.stringSerialize(com.github.tommyettinger.digital.Base base) Serializes the current state of this EnhancedRandom to a String that can be used bystringDeserialize(String)to load this state at another time.voidThe object implements the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, and arrays.Methods inherited from class java.util.Random
doubles, doubles, doubles, doubles, ints, ints, ints, ints, longs, longs, longs, longsMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface java.util.random.RandomGenerator
isDeprecated
-
Constructor Details
-
EnhancedRandom
public EnhancedRandom() -
EnhancedRandom
public EnhancedRandom(long seed)
-
-
Method Details
-
getTag
Gets the tag used to identify this type of EnhancedRandom, as a String. This tag should be unique, and for uniformity purposes, all tags used in this library are 4 characters long. User-defined tags should have a different length.- Returns:
- a unique String identifier for this type of EnhancedRandom; usually 4 chars long.
-
mainlyGeneratesInt
public boolean mainlyGeneratesInt()Returns true if this generator mainly operates via itsnextInt()method internally, which means itsnextLong()must generate twointvalues instead of naturally producing onelong. This affects how the minimum period is measured forgetMinimumPeriod(). Most generators not intentionally targeting Google Web Toolkit mainly operate vianextLong()here, and return false. A generator that returns true here does not necessarily use 32-bit math; a generator can use 64-bit math internally but only produce 32 bits at a time by truncating its results.- Returns:
- true if measurements of the period measure calls to
nextInt()instead ofnextLong() - See Also:
-
getMinimumPeriod
Gets the guaranteed lowest number of different results this can return from its main generating method, which is normallynextLong()unlessmainlyGeneratesInt()returns true (then it isnextInt()). The maximum period is not known for many generators, but the minimum is, even if it is only 1 for a generator that can be initialized badly and return the same value every time on that cycle. If the minimum period is not known, this should not be overridden; its default result is the constantBigInteger.ONE. If this is the only JavaDoc for this method, the minimum period is not known, and is possibly 1 in the worst case.
This is relevant when determining if, when two different generators are combined, their period will change. The minimum period of two generators run simultaneously and both used fully in the result is the least common multiple of their minimum periods. This can be computed conveniently withlcm(BigInteger, BigInteger)given the minimum period of two different EnhancedRandom generators.
Implementations are strongly encouraged to compute this value once, if it needs computation at all, and store it in aprivate static final BigInteger MINIMUM_PERIOD;, which this method simply returns. Classes are not required to have aMINIMUM_PERIODfield or to make it accessible. Calling this method should generally not create a new BigInteger.- Returns:
- the minimum guaranteed period, or the shortest cycle length possible for the main generating method
-
lcm
Gets the least common multiple (lcm) of two BigInteger values, which here are usually returned bygetMinimumPeriod().- Parameters:
a- must be greater than 0; typically the result ofgetMinimumPeriod()b- must be greater than 0; typically the result ofgetMinimumPeriod()- Returns:
- the least common multiple of
aandb, as a BigInteger
-
seedFromMath
public static long seedFromMath()UsesMath.random()to hastily put together a not-especially-uniformlongvalue, meant only to produce a seed when no seed was specified (the "I don't care" seed).- Returns:
- a kind-of-uniform
longvalue
-
setSeed
public abstract void setSeed(long seed) Sets the seed of this random number generator using a singlelongseed. This should behave exactly the same as if a new object of this type was created with the constructor that takes a singlelongvalue. This does not necessarily assign the state variable(s) of the implementation with the exact contents of seed, sogetSelectedState(int)should not be expected to returnseedafter this, though it may. If this implementation has more than onelongof state, then the expectation is that none of those state variables will be exactly equal toseed(almost all the time). -
getStateCount
public int getStateCount()Gets the number of possible state variables that can be selected withgetSelectedState(int)orsetSelectedState(int, long). This defaults to returning 0, making no state variable available for reading or writing. An implementation that has only onelongstate, likeDistinctRandomgenerator, should return1. A generator that permits setting two differentlongvalues, likeLaserRandom, should return2. Much larger values are possible for types like the Mersenne Twister or some CMWC generators.- Returns:
- the non-negative number of selections possible for state variables
-
getSelectedState
public long getSelectedState(int selection) Gets a selected state value from this EnhancedRandom. The number of possible selections is up to the implementing class, and is accessible viagetStateCount(), but negative values forselectionare typically not tolerated. This should return the exact value of the selected state, assuming it is implemented. The default implementation throws an UnsupportedOperationException, and implementors only have to allow reading the state if they choose to implement this differently. If this method is intended to be used,getStateCount()must also be implemented.- Parameters:
selection- used to select which state variable to get; generally non-negative- Returns:
- the exact value of the selected state
-
setSelectedState
public void setSelectedState(int selection, long value) Sets a selected state value to the given longvalue. The number of possible selections is up to the implementing class, but negative values forselectionare typically not tolerated. Implementors are permitted to changevalueif it is not valid, but they should not alter it if it is valid. The public implementation callssetSeed(long)withvalue, which doesn't need changing if the generator has one state that is set verbatim by setSeed(). Otherwise, this method should be implemented whengetSelectedState(int)is and the state is allowed to be set by users. Having accurate ways to get and set the full state of a random number generator makes it much easier to serialize and deserialize that class.- Parameters:
selection- used to select which state variable to set; generally non-negativevalue- the exact value to use for the selected state, if valid
-
setState
public void setState(long state) Sets each state variable to the givenstate. IfgetStateCount()is 1, then this should set the whole state to the given value usingsetSelectedState(int, long). If getStateCount() is more than 1, then all states will be set in the same way (using setSelectedState(), all tostate).- Parameters:
state- the long value to use for each state variable
-
setState
public void setState(long stateA, long stateB) Sets each state variable to eitherstateAorstateB, alternating. This usessetSelectedState(int, long)to set the values. If there is one state variable (getStateCount()is 1), then this only sets that state variable to stateA. If there are two state variables, the first is set to stateA, and the second to stateB. If there are more, it reuses stateA, then stateB, then stateA, and so on until all variables are set.- Parameters:
stateA- the long value to use for states at index 0, 2, 4, 6...stateB- the long value to use for states at index 1, 3, 5, 7...
-
setState
public void setState(long stateA, long stateB, long stateC) Sets each state variable tostateA,stateB, orstateC, alternating. This usessetSelectedState(int, long)to set the values. If there is one state variable (getStateCount()is 1), then this only sets that state variable to stateA. If there are two state variables, the first is set to stateA, and the second to stateB. With three state variables, the first is set to stateA, the second to stateB, and the third to stateC. If there are more, it reuses stateA, then stateB, then stateC, then stateA, and so on until all variables are set.- Parameters:
stateA- the long value to use for states at index 0, 3, 6, 9...stateB- the long value to use for states at index 1, 4, 7, 10...stateC- the long value to use for states at index 2, 5, 8, 11...
-
setState
public void setState(long stateA, long stateB, long stateC, long stateD) Sets each state variable tostateA,stateB,stateC, orstateD, alternating. This usessetSelectedState(int, long)to set the values. If there is one state variable (getStateCount()is 1), then this only sets that state variable to stateA. If there are two state variables, the first is set to stateA, and the second to stateB. With three state variables, the first is set to stateA, the second to stateB, and the third to stateC. With four state variables, the first is set to stateA, the second to stateB, the third to stateC, and the fourth to stateD. If there are more, it reuses stateA, then stateB, then stateC, then stateD, then stateA, and so on until all variables are set.- Parameters:
stateA- the long value to use for states at index 0, 4, 8, 12...stateB- the long value to use for states at index 1, 5, 9, 13...stateC- the long value to use for states at index 2, 6, 10, 14...stateD- the long value to use for states at index 3, 7, 11, 15...
-
setState
public void setState(long stateA, long stateB, long stateC, long stateD, long stateE) Sets each state variable tostateA,stateB,stateC,stateD, orstateE, alternating. This usessetSelectedState(int, long)to set the values. If there is one state variable (getStateCount()is 1), then this only sets that state variable to stateA. If there are two state variables, the first is set to stateA, and the second to stateB. With three state variables, the first is set to stateA, the second to stateB, and the third to stateC. With four state variables, the first is set to stateA, the second to stateB, the third to stateC, and the fourth to stateD. If there are more, it reuses stateA, then stateB, then stateC, then stateD, then stateE, then stateA, and so on until all variables are set.- Parameters:
stateA- the long value to use for states at index 0, 5, 10, 15...stateB- the long value to use for states at index 1, 6, 11, 16...stateC- the long value to use for states at index 2, 7, 12, 17...stateD- the long value to use for states at index 3, 8, 13, 18...stateE- the long value to use for states at index 4, 9, 14, 19...
-
setState
public void setState(long stateA, long stateB, long stateC, long stateD, long stateE, long stateF) Sets each state variable tostateA,stateB,stateC,stateD, orstateE, alternating. This usessetSelectedState(int, long)to set the values. If there is one state variable (getStateCount()is 1), then this only sets that state variable to stateA. If there are two state variables, the first is set to stateA, and the second to stateB. With three state variables, the first is set to stateA, the second to stateB, and the third to stateC. With four state variables, the first is set to stateA, the second to stateB, the third to stateC, and the fourth to stateD. If there are more, it reuses stateA, then stateB, then stateC, then stateD, then stateE, then stateF, then stateA, and so on until all variables are set.- Parameters:
stateA- the long value to use for states at index 0, 6, 12, 18...stateB- the long value to use for states at index 1, 7, 13, 19...stateC- the long value to use for states at index 2, 8, 14, 20...stateD- the long value to use for states at index 3, 9, 15, 21...stateE- the long value to use for states at index 4, 10, 16, 22...stateF- the long value to use for states at index 5, 11, 17, 23...
-
setState
public void setState(long... states) Sets all state variables to alternating values chosen fromstates. If states is empty, then this does nothing, and leaves the current generator unchanged. This works for generators with anygetStateCount(), but may allocate an array if states is used as a varargs (you can pass an existing array without needing to allocate). This usessetSelectedState(int, long)to change the states.- Parameters:
states- an array or varargs of long values to use as states
-
next
public int next(int bits) Generates the next pseudorandom number with a specific maximum size in bits (not a max number). If you want to get a random number in a range, you should usually usenextInt(int)instead. For some specific cases, this method is more efficient and less biased thannextInt(int). Forbitsvalues between 1 and 30, this should be similar in effect tonextInt(1 << bits); though it won't typically produce the same values, they will have the correct range. Ifbitsis 31, this can return any non-negativeint; note thatnextInt(1 << 31)won't behave this way because1 << 31is negative. Ifbitsis 32 (or 0), this can return anyint.The general contract of
nextis that it returns anintvalue and if the argumentbitsis between1and32(inclusive), then that many low-order bits of the returned value will be (approximately) independently chosen bit values, each of which is (approximately) equally likely to be0or1.Note that you can give this values for
bitsthat are outside its expected range of 1 to 32, but the value used, as long as bits is positive, will effectively bebits % 32. As stated before, a value of 0 for bits is the same as a value of 32. -
nextBytes
public void nextBytes(byte[] bytes) Generates random bytes and places them into a user-supplied byte array. The number of random bytes produced is equal to the length of the byte array.- Specified by:
nextBytesin interfaceRandomGenerator- Overrides:
nextBytesin classRandom- Parameters:
bytes- the byte array to fill with random bytes- Throws:
NullPointerException- if the byte array is null
-
nextInt
public int nextInt()Returns the next pseudorandom, uniformly distributedintvalue from this random number generator's sequence. The general contract ofnextIntis that oneintvalue is pseudorandomly generated and returned. All 232 possibleintvalues are produced with (approximately) equal probability.- Specified by:
nextIntin interfaceRandomGenerator- Overrides:
nextIntin classRandom- Returns:
- the next pseudorandom, uniformly distributed
intvalue from this random number generator's sequence
-
nextInt
public int nextInt(int bound) Returns a pseudorandom, uniformly distributedintvalue between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract ofnextIntis that oneintvalue in the specified range is pseudorandomly generated and returned. Allboundpossibleintvalues are produced with (approximately) equal probability.
This method clamps bound to be at least 0; it never returns a negative int.
It should be mentioned that the technique this uses has some bias, depending onbound, but it typically isn't measurable without specifically looking for it. Using the method this does allows this method to always advance the state by one step, instead of a varying and unpredictable amount with the more typical ways of rejection-sampling random numbers and only using numbers that can produce an int within the bound without bias. See M.E. O'Neill's blog about random numbers for discussion of alternative, unbiased methods.- Specified by:
nextIntin interfaceRandomGenerator- Overrides:
nextIntin classRandom- Parameters:
bound- the upper bound (exclusive). If negative or 0, this always returns 0.- Returns:
- the next pseudorandom, uniformly distributed
intvalue between zero (inclusive) andbound(exclusive) from this random number generator's sequence
-
nextUnsignedInt
public int nextUnsignedInt(int bound) Returns a pseudorandom, uniformly distributedintvalue between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract ofnextIntis that oneintvalue in the specified range is pseudorandomly generated and returned. Allboundpossibleintvalues are produced with (approximately) equal probability.
This method treats the outer bound as unsigned, so if a negative int is passed asbound, it will be treated as positive and larger thanInteger.MAX_VALUE. That means this can produce results that are positive or negative, but when you mask the result and the bound with0xFFFFFFFFL(to treat them as unsigned), the result will always be between0L(inclusive) and the masked bound (exclusive).
This is primarily useful as a building block for other methods in this class.- Parameters:
bound- the upper bound (exclusive); treated as unsigned- Returns:
- the next pseudorandom, uniformly distributed
intvalue between zero (inclusive) andbound(exclusive), treated as unsigned, from this random number generator's sequence
-
nextSignedInt
public int nextSignedInt(int outerBound) Returns a pseudorandom, uniformly distributedintvalue between an inner bound of 0 (inclusive) and the specifiedouterBound(exclusive). This is meant for cases where the outer bound may be negative, especially if the bound is unknown or may be user-specified. A negative outer bound is used as the lower bound; a positive outer bound is used as the upper bound. An outer bound of -1, 0, or 1 will always return 0, keeping the bound exclusive (except for outer bound 0). This method is slightly slower thannextInt(int).- Parameters:
outerBound- the outer exclusive bound; may be any int value, allowing negative- Returns:
- a pseudorandom int between 0 (inclusive) and outerBound (exclusive)
- See Also:
-
nextInt
public int nextInt(int innerBound, int outerBound) Returns a pseudorandom, uniformly distributedintvalue between the specifiedinnerBound(inclusive) and the specifiedouterBound(exclusive). IfouterBoundis less than or equal toinnerBound, this always returnsinnerBound.
For any case where outerBound might be valid but less than innerBound, you can usenextSignedInt(int, int). If outerBound is less than innerBound here, this simply returns innerBound.- Specified by:
nextIntin interfaceRandomGenerator- Parameters:
innerBound- the inclusive inner bound; may be any int, allowing negativeouterBound- the exclusive outer bound; must be greater than innerBound (otherwise this returns innerBound)- Returns:
- a pseudorandom int between innerBound (inclusive) and outerBound (exclusive)
- See Also:
-
nextSignedInt
public int nextSignedInt(int innerBound, int outerBound) Returns a pseudorandom, uniformly distributedintvalue between the specifiedinnerBound(inclusive) and the specifiedouterBound(exclusive). This is meant for cases where either bound may be negative, especially if the bounds are unknown or may be user-specified.- Parameters:
innerBound- the inclusive inner bound; may be any int, allowing negativeouterBound- the exclusive outer bound; may be any int, allowing negative- Returns:
- a pseudorandom int between innerBound (inclusive) and outerBound (exclusive)
- See Also:
-
nextLong
public abstract long nextLong()Returns the next pseudorandom, uniformly distributedlongvalue from this random number generator's sequence. The general contract ofnextLongis that onelongvalue is pseudorandomly generated and returned.
The only methods that need to be implemented by this interface are this andcopy(), though other methods can be implemented as appropriate for generators that, for instance, natively produce ints rather than longs.- Specified by:
nextLongin interfaceRandomGenerator- Overrides:
nextLongin classRandom- Returns:
- the next pseudorandom, uniformly distributed
longvalue from this random number generator's sequence
-
nextLong
public long nextLong(long bound) Returns a pseudorandom, uniformly distributedlongvalue between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract ofnextLongis that onelongvalue in the specified range is pseudorandomly generated and returned. Allboundpossiblelongvalues are produced with (approximately) equal probability, though there is a small amount of bias depending on the bound.
Note that this advances the state by the same amount as a single call tonextLong(), which allows methods likeskip(long)to function correctly, but introduces some bias whenboundis very large. This will also advance the state ifboundis 0 or negative, so usage with a variable bound will advance the state reliably.
This method has some bias, particularly on larger bounds. Actually measuring bias with bounds in the trillions or greater is challenging but not impossible, so don't use this for a real-money gambling purpose. The bias isn't especially significant, though.- Specified by:
nextLongin interfaceRandomGenerator- Parameters:
bound- the upper bound (exclusive). If negative or 0, this always returns 0.- Returns:
- the next pseudorandom, uniformly distributed
longvalue between zero (inclusive) andbound(exclusive) from this random number generator's sequence - See Also:
-
nextSignedLong
public long nextSignedLong(long outerBound) Returns a pseudorandom, uniformly distributedlongvalue between an inner bound of 0 (inclusive) and the specifiedouterBound(exclusive). This is meant for cases where the outer bound may be negative, especially if the bound is unknown or may be user-specified. A negative outer bound is used as the lower bound; a positive outer bound is used as the upper bound. An outer bound of -1, 0, or 1 will always return 0, keeping the bound exclusive (except for outer bound 0).Note that this advances the state by the same amount as a single call to
nextLong(), which allows methods likeskip(long)to function correctly, but introduces some bias whenboundis very large. This method should be about as fast asnextLong(long), unlike the speed difference betweennextInt(int)andnextSignedInt(int).- Parameters:
outerBound- the outer exclusive bound; may be any long value, allowing negative- Returns:
- a pseudorandom long between 0 (inclusive) and outerBound (exclusive)
- See Also:
-
nextLong
public long nextLong(long inner, long outer) Returns a pseudorandom, uniformly distributedlongvalue between the specifiedinnerBound(inclusive) and the specifiedouterBound(exclusive). IfouterBoundis less than or equal toinnerBound, this always returnsinnerBound.
For any case where outerBound might be valid but less than innerBound, you can usenextSignedLong(long, long).- Specified by:
nextLongin interfaceRandomGenerator- Parameters:
inner- the inclusive inner bound; may be any long, allowing negativeouter- the exclusive outer bound; must be greater than innerBound (otherwise this returns innerBound)- Returns:
- a pseudorandom long between innerBound (inclusive) and outerBound (exclusive)
- See Also:
-
nextSignedLong
public long nextSignedLong(long inner, long outer) Returns a pseudorandom, uniformly distributedlongvalue between the specifiedinnerBound(inclusive) and the specifiedouterBound(exclusive). This is meant for cases where either bound may be negative, especially if the bounds are unknown or may be user-specified.- Parameters:
inner- the inclusive inner bound; may be any long, allowing negativeouter- the exclusive outer bound; may be any long, allowing negative- Returns:
- a pseudorandom long between innerBound (inclusive) and outerBound (exclusive)
- See Also:
-
nextBoolean
public boolean nextBoolean()Returns the next pseudorandom, uniformly distributedbooleanvalue from this random number generator's sequence. The general contract ofnextBooleanis that onebooleanvalue is pseudorandomly generated and returned. The valuestrueandfalseare produced with (approximately) equal probability.
The public implementation simply returns a sign check onnextLong(), returning true if the generated long is negative. This is typically the safest way to implement this method; many types of generators have less statistical quality on their lowest bit, so just returning based on the lowest bit isn't always a good idea.- Specified by:
nextBooleanin interfaceRandomGenerator- Overrides:
nextBooleanin classRandom- Returns:
- the next pseudorandom, uniformly distributed
booleanvalue from this random number generator's sequence
-
nextFloat
public float nextFloat()Returns the next pseudorandom, uniformly distributedfloatvalue between0.0(inclusive) and1.0(exclusive) from this random number generator's sequence.The general contract of
nextFloatis that onefloatvalue, chosen (approximately) uniformly from the range0.0f(inclusive) to1.0f(exclusive), is pseudorandomly generated and returned. All 224 possiblefloatvalues of the form m x 2-24, where m is a positive integer less than 224, are produced with (approximately) equal probability.The public implementation uses the upper 24 bits of
nextLong(), with an unsigned right shift and a multiply by a very small float (5.9604645E-8for0x1p-24f). It tends to be fast if nextLong() is fast, but alternative implementations could use 24 bits ofnextInt()(or justnext(int), giving it24) if that generator doesn't efficiently generate 64-bit longs.- Specified by:
nextFloatin interfaceRandomGenerator- Overrides:
nextFloatin classRandom- Returns:
- the next pseudorandom, uniformly distributed
floatvalue between0.0and1.0from this random number generator's sequence
-
nextFloat
public float nextFloat(float outerBound) Gets a pseudo-random float between 0 (inclusive) andouterBound(exclusive). The outerBound may be positive or negative. Exactly the same asnextFloat() * outerBound.- Specified by:
nextFloatin interfaceRandomGenerator- Parameters:
outerBound- the exclusive outer bound- Returns:
- a float between 0 (inclusive) and
outerBound(exclusive)
-
nextFloat
public float nextFloat(float innerBound, float outerBound) Gets a pseudo-random float betweeninnerBound(inclusive) andouterBound(exclusive). Either, neither, or both of innerBound and outerBound may be negative; this does not change which is inclusive and which is exclusive.- Specified by:
nextFloatin interfaceRandomGenerator- Parameters:
innerBound- the inclusive inner bound; may be negativeouterBound- the exclusive outer bound; may be negative- Returns:
- a float between
innerBound(inclusive) andouterBound(exclusive)
-
nextDouble
public double nextDouble()Returns the next pseudorandom, uniformly distributeddoublevalue between0.0(inclusive) and1.0(exclusive) from this random number generator's sequence.The general contract of
nextDoubleis that onedoublevalue, chosen (approximately) uniformly from the range0.0d(inclusive) to1.0d(exclusive), is pseudorandomly generated and returned.The public implementation uses the upper 53 bits of
nextLong(), with an unsigned right shift and a multiply by a very small double (1.1102230246251565E-16, or0x1p-53). It should perform well if nextLong() performs well, and is expected to perform less well if the generator naturally produces 32 or fewer bits at a time.- Specified by:
nextDoublein interfaceRandomGenerator- Overrides:
nextDoublein classRandom- Returns:
- the next pseudorandom, uniformly distributed
doublevalue between0.0and1.0from this random number generator's sequence
-
nextDouble
public double nextDouble(double outerBound) Gets a pseudo-random double between 0 (inclusive) andouterBound(exclusive). The outerBound may be positive or negative. Exactly the same asnextDouble() * outerBound.- Specified by:
nextDoublein interfaceRandomGenerator- Parameters:
outerBound- the exclusive outer bound- Returns:
- a double between 0 (inclusive) and
outerBound(exclusive)
-
nextDouble
public double nextDouble(double innerBound, double outerBound) Gets a pseudo-random double betweeninnerBound(inclusive) andouterBound(exclusive). Either, neither, or both of innerBound and outerBound may be negative; this does not change which is inclusive and which is exclusive.- Specified by:
nextDoublein interfaceRandomGenerator- Parameters:
innerBound- the inclusive inner bound; may be negativeouterBound- the exclusive outer bound; may be negative- Returns:
- a double between
innerBound(inclusive) andouterBound(exclusive)
-
nextInclusiveDouble
public double nextInclusiveDouble()This is just likenextDouble(), returning a double between 0 and 1, except that it is inclusive on both 0.0 and 1.0. It returns 1.0 rarely, 0.000000000000000005421010862427522% of the time if there is no bias in the generator, but it can happen.
This method does not return purely-equidistant doubles, because there the resolution of possible doubles it can generate is higher as it approaches 0.0 . The smallest non-zero double this can return is 2.710505431213763e-20 (0x1.0000000000003p-65 in hex), and the largest non-one double this can return is 0.9999999999999999 (0x1.fffffffffffffp-1 in hex). This uses nearly identical code tonextExclusiveDouble(), but does some really unusual operations on both the bits and the double value to be able to produce 0.0 and 1.0 . This retains the exclusive version's quality of having approximately uniform distributions for every mantissa bit, unlike most ways of generating random floating-point numbers.- Returns:
- a double between 0.0, inclusive, and 1.0, inclusive
-
nextInclusiveDouble
public double nextInclusiveDouble(double outerBound) Just likenextDouble(double), but this is inclusive on both 0.0 andouterBound. It may be important to note that it returns outerBound on only 0.000000000000011102230246251565% of calls.- Parameters:
outerBound- the outer inclusive bound; may be positive or negative- Returns:
- a double between 0.0, inclusive, and
outerBound, inclusive
-
nextInclusiveDouble
public double nextInclusiveDouble(double innerBound, double outerBound) Just likenextDouble(double, double), but this is inclusive on bothinnerBoundandouterBound. It may be important to note that it returns outerBound on only 0.000000000000011102230246251565% of calls, if it can return it at all because of floating-point imprecision when innerBound is a larger number.- Parameters:
innerBound- the inner inclusive bound; may be positive or negativeouterBound- the outer inclusive bound; may be positive or negative- Returns:
- a double between
innerBound, inclusive, andouterBound, inclusive
-
nextInclusiveFloat
public float nextInclusiveFloat()This is just likenextFloat(), returning a float between 0 and 1, except that it is inclusive on both 0.0 and 1.0. It returns 1.0 rarely, 0.000000000000000005421010862427522% of the time if there is no bias in the generator, but it can happen.
This method does not return purely-equidistant floats, because there the resolution of possible floats it can generate is higher as it approaches 0.0 . The smallest non-zero float this can return is 2.7105064E-20 (0x1.000006p-65 in hex), and the largest non-one float this can return is 0.99999994f (0x1.fffffep-1 in hex). This uses nearly identical code tonextExclusiveFloat(), but does some really unusual operations on both the bits and the float value to be able to produce 0.0f and 1.0f . This retains the exclusive version's quality of having approximately uniform distributions for every mantissa bit, unlike most ways of generating random floating-point numbers.- Returns:
- a float between 0.0, inclusive, and 1.0, inclusive
-
nextInclusiveFloat
public float nextInclusiveFloat(float outerBound) Just likenextFloat(float), but this is inclusive on both 0.0 andouterBound. It may be important to note that it returns outerBound on only 0.00000596046412226771% of calls.- Parameters:
outerBound- the outer inclusive bound; may be positive or negative- Returns:
- a float between 0.0, inclusive, and
outerBound, inclusive
-
nextInclusiveFloat
public float nextInclusiveFloat(float innerBound, float outerBound) Just likenextFloat(float, float), but this is inclusive on bothinnerBoundandouterBound. It may be important to note that it returns outerBound on only 0.00000596046412226771% of calls, if it can return it at all because of floating-point imprecision when innerBound is a larger number.- Parameters:
innerBound- the inner inclusive bound; may be positive or negativeouterBound- the outer inclusive bound; may be positive or negative- Returns:
- a float between
innerBound, inclusive, andouterBound, inclusive
-
nextExclusiveDouble
public double nextExclusiveDouble()Gets a random double between 0.0 and 1.0, exclusive at both ends; this method is also more uniform thannextDouble()if you use the bit-patterns of the returned doubles. This is a simplified version of this algorithm by Allen Downey. This can return double values between 2.710505431213761E-20 and 0.9999999999999999, or 0x1.0p-65 and 0x1.fffffffffffffp-1 in hex notation. It cannot return 0 or 1. Some cases can prefernextExclusiveDoubleEquidistant(), which is implemented more traditionally but may have slower performance. This method can also return doubles that are extremely close to 0, but can't return doubles that are as close to 1, due to how floating-point numbers work. However, nextExclusiveDoubleEquidistant() can return only a minimum value that is as distant from 0 as its maximum value is distant from 1.
To compare, nextDouble() and nextExclusiveDoubleEquidistant() are less likely to produce a "1" bit for their lowest 5 bits of mantissa/significand (the least significant bits numerically, but potentially important for some uses), with the least significant bit produced half as often as the most significant bit in the mantissa. As for this method, it has approximately the same likelihood of producing a "1" bit for any position in the mantissa.
The implementation may have different performance characteristics thannextDouble(), because this doesn't perform any floating-point multiplication or division, and instead assembles bits obtained by one call tonextLong(). This usesBitConversion.longBitsToDouble(long)andBitConversion.countLeadingZeros(long), both of which typically have optimized intrinsics on HotSpot, and this is branchless and loopless, unlike the original algorithm by Allen Downey. When compared withnextExclusiveDoubleEquidistant(), this method performs better on at least HotSpot JVMs. On GraalVM 17, this is over twice as fast as nextExclusiveDoubleEquidistant().- Returns:
- a random uniform double between 2.710505431213761E-20 and 0.9999999999999999 (both inclusive)
-
nextExclusiveDoubleEquidistant
public double nextExclusiveDoubleEquidistant()Gets a random double between 0.0 and 1.0, exclusive at both ends. This can return double values between 1.1102230246251565E-16 and 0.9999999999999999, or 0x1.0p-53 and 0x1.fffffffffffffp-1 in hex notation. It cannot return 0 or 1, and its minimum and maximum results are equally distant from 0 and from 1, respectively. Many usages may prefernextExclusiveDouble(), which is better-distributed if you consider the bit representation of the returned doubles, tends to perform better, and can return doubles that much closer to 0 than this can.
The implementation simply usesnextLong(long)to get a uniformly-chosen long between 1 and (2 to the 53) - 1, both inclusive, and multiplies it by (2 to the -53). Using larger values than (2 to the 53) would cause issues with the double math.- Returns:
- a random uniform double between 0 and 1 (both exclusive)
-
nextExclusiveDouble
public double nextExclusiveDouble(double outerBound) Just likenextDouble(double), but this is exclusive on both 0.0 andouterBound. LikenextExclusiveDouble(), which this uses, this may have better bit-distribution of double values, and it may also be better able to produce very small doubles whenouterBoundis large. It should typically be a little faster thannextDouble(double).- Parameters:
outerBound- the outer exclusive bound; may be positive or negative- Returns:
- a double between 0.0, exclusive, and
outerBound, exclusive
-
nextExclusiveDouble
public double nextExclusiveDouble(double innerBound, double outerBound) Just likenextDouble(double, double), but this is exclusive on bothinnerBoundandouterBound. LikenextExclusiveDouble(), which this uses,, this may have better bit-distribution of double values, and it may also be better able to produce doubles close to innerBound whenouterBound - innerBoundis large. It should typically be a little faster thannextDouble(double, double).- Parameters:
innerBound- the inner exclusive bound; may be positive or negativeouterBound- the outer exclusive bound; may be positive or negative- Returns:
- a double between
innerBound, exclusive, andouterBound, exclusive
-
nextExclusiveSignedDouble
public double nextExclusiveSignedDouble()Gets a random double that may be positive or negative, but cannot be 0, and always has a magnitude less than 1.
This is a modified version of this algorithm by Allen Downey. This version can return double values between -0.9999999999999999 and -5.421010862427522E-20, as well as between 5.421010862427522E-20 and 0.9999999999999999, or -0x1.fffffffffffffp-1 to -0x1.0p-64 as well as between 0x1.0p-64 and 0x1.fffffffffffffp-1 in hex notation. It cannot return -1, 0 or 1. It has much more uniform bit distribution across its mantissa/significand bits thanRandom.nextDouble(), especially when the result of nextDouble() is expanded to the -1.0 to 1.0 range (such as with2.0 * (nextDouble() - 0.5)). Where that code usingnextDouble()is unable to produce a "1" bit for its lowest bit of mantissa (the least significant bits numerically, but potentially important for some uses), this has approximately the same likelihood of producing a "1" bit for any positions in the mantissa, and also equal odds for the sign bit.
Some useful properties here are that this produces a negative result exactly as often as the underlying generator produces a negative result withnextLong(), and the least-significant bits that the underlying generator produces withnextLong()are also the least-significant in magnitude here. This could be used with lower-quality randomness, like a linear congruential generator, and the flaws those have with their low-order bits would barely affect floating-point results here. This generator also produces results that are symmetrical around 0.0, with every possible positive number having a possible negative number of equal magnitude, if the underlying generator is at least 1-dimensionally equidistributed. Note that generators such asXoroshiro128StarStarRandomandXoshiro256StarStarRandomcannot return 0L fromnextLong()as frequently as other results, so this is not (technically) true of those. Those generators (and other LFSR-type generators) will produce 5.421010862427522E-20 less frequently than -5.421010862427522E-20 .- Returns:
- a random uniform double between -1 and 1 with a tiny hole around 0 (all exclusive)
-
nextExclusiveFloat
public float nextExclusiveFloat()Gets a random float between 0.0 and 1.0, exclusive at both ends. This method is also more uniform thannextFloat()if you use the bit-patterns of the returned floats. This is a simplified version of this algorithm by Allen Downey. This version can return float values between 2.7105054E-20 to 0.99999994, or 0x1.0p-65 to 0x1.fffffep-1 in hex notation. It cannot return 0 or 1. To compare, nextFloat() is less likely to produce a "1" bit for its lowest 5 bits of mantissa/significand (the least significant bits numerically, but potentially important for some uses), with the least significant bit produced half as often as the most significant bit in the mantissa. As for this method, it has approximately the same likelihood of producing a "1" bit for any position in the mantissa.
The implementation may have different performance characteristics thannextFloat(), because this doesn't perform any floating-point multiplication or division, and instead assembles bits obtained by one call tonextLong(). This usesBitConversion.intBitsToFloat(int)andBitConversion.countLeadingZeros(long), both of which typically have optimized intrinsics on HotSpot, and this is branchless and loopless, unlike the original algorithm by Allen Downey. When compared withnextExclusiveFloatEquidistant(), this method performs better on at least HotSpot JVMs. On GraalVM 17, this is over twice as fast as nextExclusiveFloatEquidistant().- Returns:
- a random uniform float between 0 and 1 (both exclusive)
-
nextExclusiveFloatEquidistant
public float nextExclusiveFloatEquidistant()Gets a random float between 0.0 and 1.0, exclusive at both ends. This can return float values between 5.9604645E-8 and 0.99999994, or 0x1.0p-24 and 0x1.fffffep-1 in hex notation. It cannot return 0 or 1, and its minimum and maximum results are equally distant from 0 and from 1, respectively. Most usages might prefernextExclusiveFloat(), which is better-distributed if you consider the bit representation of the returned floats, tends to perform better, and can return floats that much closer to 0 than this can.
The implementation simply usesnextInt(int)to get a uniformly-chosen int between 1 and (2 to the 24) - 1, both inclusive, and multiplies it by (2 to the -24). Using larger values than (2 to the 24) would cause issues with the float math.- Returns:
- a random uniform float between 0 and 1 (both exclusive)
-
nextExclusiveFloat
public float nextExclusiveFloat(float outerBound) Just likenextFloat(float), but this is exclusive on both 0.0 andouterBound. LikenextExclusiveFloat(), this may have better bit-distribution of float values, and it may also be better able to produce very small floats whenouterBoundis large. It should be a little faster thannextFloat(float).- Parameters:
outerBound- the outer exclusive bound; may be positive or negative- Returns:
- a float between 0.0, exclusive, and
outerBound, exclusive
-
nextExclusiveFloat
public float nextExclusiveFloat(float innerBound, float outerBound) Just likenextFloat(float, float), but this is exclusive on bothinnerBoundandouterBound. LikenextExclusiveFloat(), this may have better bit-distribution of float values, and it may also be better able to produce floats close to innerBound whenouterBound - innerBoundis large. It should be a little faster thannextFloat(float, float).- Parameters:
innerBound- the inner exclusive bound; may be positive or negativeouterBound- the outer exclusive bound; may be positive or negative- Returns:
- a float between
innerBound, exclusive, andouterBound, exclusive
-
nextExclusiveSignedFloat
public float nextExclusiveSignedFloat()Gets a random float that may be positive or negative, but cannot be 0, and always has a magnitude less than 1.
This is a modified version of this algorithm by Allen Downey. This version can return float values between -0.99999994 and -5.421011E-20, as well as between 5.421011E-20 and 0.99999994, or -0x1.fffffep-1 to -0x1.0p-64 as well as between 0x1.0p-64 and 0x1.fffffep-1 in hex notation. It cannot return -1, 0 or 1. It has much more uniform bit distribution across its mantissa/significand bits thanRandom.nextFloat(), especially when the result of nextFloat() is expanded to the -1.0 to 1.0 range (such as with2.0 * (nextFloat() - 0.5)). Where the given example code is unable to produce a "1" bit for its lowest bit of mantissa (the least significant bits numerically, but potentially important for some uses), this has approximately the same likelihood of producing a "1" bit for any positions in the mantissa, and also equal odds for the sign bit.
Some useful properties here are that this produces a negative result exactly as often as the underlying generator produces a negative result withnextLong(), and the least-significant bits that the underlying generator produces withnextLong()are also the least-significant in magnitude here. This could be used with lower-quality randomness, like a linear congruential generator, and the flaws those have with their low-order bits would barely affect floating-point results here. This generator also produces results that are symmetrical around 0.0, with every possible positive number having a possible negative number of equal magnitude, if the underlying generator is at least 1-dimensionally equidistributed. Note that generators such asXoroshiro128StarStarRandomandXoshiro256StarStarRandomcannot return 0L fromnextLong()as frequently as other results, so this is not (technically) true of those. Those generators (and other LFSR-type generators) will produce 5.421011E-20 less frequently than -5.421011E-20 .- Returns:
- a random uniform float between -1 and 1 with a tiny hole around 0 (all exclusive)
-
nextGaussian
public double nextGaussian()Returns the next pseudorandom, Gaussian ("normally") distributeddoublevalue with mean0.0and standard deviation1.0from this random number generator's sequence.The general contract of
nextGaussianis that onedoublevalue, chosen from (approximately) the usual normal distribution with mean0.0and standard deviation1.0, is pseudorandomly generated and returned.This does not use a rough approximation, which is a departure from earlier versions; instead, it uses the Ziggurat method, which produces high-quality variables very quickly. Like earlier versions that used probit() or a bit-counting approximation, this requests exactly one long from the generator's sequence (using
nextLong()). This makes it different from code like java.util.Random's nextGaussian() method, which can (rarely) fetch a higher number of random doubles.The implementation here was ported from code by Olaf Berstein, based on a paper by Jorgen A. Doornik and some steps from a paper by George Marsaglia.
Distributorhas more information, for the curious.- Specified by:
nextGaussianin interfaceRandomGenerator- Overrides:
nextGaussianin classRandom- Returns:
- the next pseudorandom, Gaussian ("normally") distributed
doublevalue with mean0.0and standard deviation1.0from this random number generator's sequence
-
nextGaussian
public double nextGaussian(double mean, double stddev) Returns the next pseudorandom, Gaussian ("normally") distributeddoublevalue with the specified mean and standard deviation from this random number generator's sequence.
This defaults to simply returningmean + stddev * nextGaussian().- Specified by:
nextGaussianin interfaceRandomGenerator- Parameters:
mean- the mean of the Gaussian distribution to be drawn fromstddev- the standard deviation (square root of the variance) of the Gaussian distribution to be drawn from- Returns:
- a Gaussian distributed
doublewith the specified mean and standard deviation
-
nextGaussianFloat
public float nextGaussianFloat()Returns the next pseudorandom, Gaussian ("normally") distributedfloatvalue with mean0.0and standard deviation1.0from this random number generator's sequence.The general contract of
nextGaussianFloatis that onefloatvalue, chosen from (approximately) the usual normal distribution with mean0.0and standard deviation1.0, is pseudorandomly generated and returned.This uses
RoughMath.normalRough(long), which actually appears to approximate the normal distribution better thanDistributor.normalF(long), though not quite as well asDistributor.normal(long)(which is used bynextGaussian()). Like nextGaussian(), this requests exactly one long from the generator's sequence (usingnextLong()). This makes it different from code like java.util.Random's nextGaussian() method, which can (rarely) fetch an arbitrarily higher number of random doubles.The implementation here was ported from code by Marc B. Reynolds and modified to only require one call to
nextLong().- Returns:
- the next pseudorandom, Gaussian ("normally") distributed
floatvalue with mean0.0and standard deviation1.0from this random number generator's sequence
-
nextGaussianFloat
public float nextGaussianFloat(float mean, float stddev) Returns the next pseudorandom, Gaussian ("normally") distributedfloatvalue with the specified mean and standard deviation from this random number generator's sequence.
This defaults to simply returningmean + stddev * nextGaussianFloat().- Parameters:
mean- the mean of the Gaussian distribution to be drawn fromstddev- the standard deviation (square root of the variance) of the Gaussian distribution to be drawn from- Returns:
- a Gaussian distributed
floatwith the specified mean and standard deviation
-
nextExponential
public double nextExponential()Returns a non-negativedoublevalue pseudorandomly chosen from an exponential distribution whose mean is 1.- Specified by:
nextExponentialin interfaceRandomGenerator- Returns:
- a non-negative
doublevalue pseudorandomly chosen from an exponential distribution with a mean of 1
-
skip
public long skip(long advance) Optional; advances or rolls back theEnhancedRandom' state without actually generating each number. Skips forward or backward a number of steps specified by advance, where a step is equal to one call tonextLong(), and returns the random number produced at that step. Negative numbers can be used to step backward, or 0 can be given to get the most-recently-generated long fromnextLong().The public implementation throws an UnsupportedOperationException. Many types of random number generator do not have an efficient way of skipping arbitrarily through the state sequence, and those types should not implement this method differently.
- Parameters:
advance- Number of future generations to skip over; can be negative to backtrack, 0 gets the most-recently-generated number- Returns:
- the random long generated after skipping forward or backwards by
advancenumbers
-
previousLong
public long previousLong()Optional; moves the state to its previous value and returns the previous long that would have been produced bynextLong(). This can be equivalent to callingskip(long)with -1L, but not always; many generators can't efficiently skip long distances, but can step back by one value.
Generators that natively generateintresults typically producelongvalues by generating an int for the high 32 bits and an int for the low 32 bits. When producing the previous long, the order the high and low bits are generated, such as bypreviousInt(), should be reversed. Generators that natively producelongvalues usually don't need to implementpreviousInt(), but those that produceintusually should implement it, and may optionally call previousInt() twice in this method.
If you know how to implement the reverse of a particular random number generator, it is recommended you do so here, rather than rely on skip(). This isn't always easy, but should always be possible for any decent PRNG (some historical PRNGs, such as the Middle-Square PRNG, cannot be reversed at all). If a generator cannot be reversed because multiple initial states can transition to the same subsequent state, it is known to have statistical problems that are not necessarily present in a generator that matches one initial state to one subsequent state.
The public implementation callsskip(long)with -1L, and if skip() has not been implemented differently, then it will throw an UnsupportedOperationException.- Returns:
- the previous number this would have produced with
nextLong()
-
previousInt
public int previousInt()Optional; moves the state to its previous value and returns the previous int that would have been produced bynextInt(). This can be equivalent to callingpreviousLong()and casting to int, but not always; generators that natively generateintresults typically move the state once in nextInt() and twice in nextLong(), and should move the state back once here.
IfnextInt()is implemented using a call tonextLong(), the implementation in this class is almost always sufficient and correct. If nextInt() changes state differently from nextLong(), then this should be implemented, if feasible, andpreviousLong()can be implemented using this method. If you know how to implement the reverse of a particular random number generator, it is recommended you do so here, rather than rely on skip(). This isn't always easy, but should always be possible for any decent PRNG (some historical PRNGs, such as the Middle-Square PRNG, cannot be reversed at all). If a generator cannot be reversed because multiple initial states can transition to the same subsequent state, it is known to have statistical problems that are not necessarily present in a generator that matches one initial state to one subsequent state.
The public implementation callspreviousLong()and casts it to int, and if previousLong() and skip() have not been implemented differently, then it will throw an UnsupportedOperationException.- Returns:
- the previous number this would have produced with
nextInt()
-
copy
Creates a new EnhancedRandom with identical states to this one, so if the same EnhancedRandom methods are called on this object and its copy (in the same order), the same outputs will be produced. This is not guaranteed to copy the inherited state of any parent class, so if you call methods that are only implemented by a superclass (likeRandom) and not this one, the results may differ.- Returns:
- a deep copy of this EnhancedRandom.
-
setWith
Similar tocopy(), but fills this EnhancedRandom with the state of another EnhancedRandom, usually (but not necessarily) one of the same type. If this class has the samegetStateCount()as other's class, then this method copies the full state of other into this object. Otherwise, if this class has a larger state count than other's class, then all of other's state is copied into the same selections in this object, and the rest of this object's state is filled with-1LusingsetSelectedState(int, long). If this class has a smaller state count than other's class, then only part of other's state is copied, and this method stops when all of this object's states have been assigned.
If this class has restrictions on its state, they will be respected by the public implementation of this method as long assetSelectedState(int, long)behaves correctly for those restrictions. Note that this method will public to throwing an UnsupportedOperationException unlessgetSelectedState(int)is implemented by other so its state can be accessed. This may also behave badly ifsetSelectedState(int, long)isn't implemented (it may be fine for some cases where the state count is 1, but don't count on it). If other's class doesn't implementgetStateCount(), then this method sets the entire state of this object to -1L; if this class doesn't implement getStateCount(), then this method does nothing.- Parameters:
other- another EnhancedRandom, typically with the same class as this one, to copy its state into this
-
probit
public static double probit(double d) A way of taking a double in the (0.0, 1.0) range and mapping it to a Gaussian or normal distribution, so high inputs correspond to high outputs, and similarly for the low range. This is centered on 0.0 and its standard deviation seems to be 1.0 (the same asRandom.nextGaussian()). If this is given an input of 0.0 or less, it returns -38.5, which is slightly less than the result when givenDouble.MIN_VALUE. If it is given an input of 1.0 or more, it returns 38.5, which is significantly larger than the result when given the largest double less than 1.0 (this value is further from 1.0 thanDouble.MIN_VALUEis from 0.0). If givenDouble.NaN, it returns whateverMath.copySign(double, double)returns for the arguments38.5, Double.NaN, which is implementation-dependent. It uses an algorithm by Peter John Acklam, as implemented by Sherali Karimov. Original source. Information on the algorithm. Wikipedia's page on the probit function may help, but is more likely to just be confusing.
Acklam's algorithm and Karimov's implementation are both quite fast. This appears faster than generating Gaussian-distributed numbers using either the Box-Muller Transform or Marsaglia's Polar Method, though it isn't as precise and can't produce as extreme min and max results in the extreme cases they should appear. If given a typical uniform randomdoublethat's exclusive on 1.0, it won't produce a result higher than8.209536145151493, and will only produce results of at least-8.209536145151493if 0.0 is excluded from the inputs (if 0.0 is an input, the result is-38.5). A chief advantage of using this with a random number generator is that it only requires one random double to obtain one Gaussian value;Random.nextGaussian()generates at least two random doubles for each two Gaussian values, but may rarely require much more random generation. Note that this method isn't used by default fornextGaussian(), because it uses a very different approximation that is faster but less precise.
This can be used both as an optimization for generating Gaussian random values, and as a way of generating Gaussian values that match a pattern present in the inputs (which you could have by using a sub-random sequence as the input, such as those produced by a van der Corput, Halton, Sobol or R2 sequence). Most methods of generating Gaussian values (e.g. Box-Muller and Marsaglia polar) do not have any way to preserve a particular pattern.- Parameters:
d- should be between 0 and 1, exclusive, but other values are tolerated- Returns:
- a normal-distributed double centered on 0.0; all results will be between -38.5 and 38.5, both inclusive
-
fixGamma
public static long fixGamma(long gamma) Attempts to improve the quality of a "gamma" increment for an additive sequence. This is stricter than the checks in Java 8's SplittableRandom. The goal here is to make sure the gamma is "sufficiently random" to avoid patterns when used as an increment. Examples of gamma values that aren't random enough include1L,3L,0xFFFFFFFFFFFFFFFFL,0xAAAAAAAAAAAAAAABL, and so on. It rejects any gamma value where any of four bit counts are less than 24 or greater than 40. The values that have their bits counted are:- The gamma itself,
- The Gray code of the gamma, defined as
(gamma ^ (gamma >>> 1)), - The
MathTools.modularMultiplicativeInverse(long)of the gamma, - And the Gray code of the above inverse of the gamma.
This simply callsfixGamma(long, int)with the given gamma and a threshold of 8.- Parameters:
gamma- any long, though almost always an odd number, that would be added as an increment in a sequence- Returns:
- gamma or a modification upon it such that its bits are "sufficiently random" to be a good increment
- See Also:
-
fixGamma
public static long fixGamma(long gamma, int threshold) Attempts to improve the quality of a "gamma" increment for an additive sequence. This is stricter than the checks in Java 8's SplittableRandom. The goal here is to make sure the gamma is "sufficiently random" to avoid patterns when used as an increment. Examples of gamma values that aren't random enough include1L,3L,0xFFFFFFFFFFFFFFFFL,0xAAAAAAAAAAAAAAABL, and so on. It rejects any gamma value where any of four bit counts are less than32 - thresholdor greater than32 + threshold. The values that have their bits counted are:- The gamma itself,
- The Gray code of the gamma, defined as
(gamma ^ (gamma >>> 1)), - The
MathTools.modularMultiplicativeInverse(long)of the gamma, - And the Gray code of the above inverse of the gamma.
- Parameters:
gamma- any long, though almost always an odd number, that would be added as an increment in a sequencethreshold- the maximum acceptable "score" as evaluated byrateGamma(long)- Returns:
- gamma or a modification upon it such that its bits are "sufficiently random" to be a good increment
- See Also:
-
rateGamma
public static int rateGamma(long gamma) Attempts to check the quality of a "gamma" increment for an additive sequence. This is stricter than the checks in Java 8's SplittableRandom. The goal here is to see if the gamma is "sufficiently random" to avoid patterns when used as an increment. Examples of gamma values that aren't random enough include1L,3L,0xFFFFFFFFFFFFFFFFL,0xAAAAAAAAAAAAAAABL, and so on. It returns the "score" for any gamma value, where the score is the maximum difference of four bit counts from an ideal of 32. The values that have their bits counted are:- The gamma itself,
- The Gray code of the gamma, defined as
(gamma ^ (gamma >>> 1)), - The
MathTools.modularMultiplicativeInverse(long)of the gamma, - And the Gray code of the above inverse of the gamma.
If the given gamma is even, it is not suitable as a SplitMix gamma automatically, and the maximum (worst) rating is returned, 32.- Parameters:
gamma- any long, though almost always an odd number, that would be added as an increment in a sequence- Returns:
- how far the given gamma is from an optimal score of 0
- See Also:
-
areEqual
Given two EnhancedRandom objects that could have the same or different classes, this returns true if they have the same class and same state, or false otherwise. Both of the arguments should implementgetSelectedState(int), or this will throw an UnsupportedOperationException. This can be useful for comparing EnhancedRandom classes that do not implement equals(), for whatever reason. This returns true if both arguments are null, but false if only one is null.- Parameters:
left- an EnhancedRandom to compare for equalityright- another EnhancedRandom to compare for equality- Returns:
- true if the two EnhancedRandom objects have the same class and state, or false otherwise
-
nextBoolean
public boolean nextBoolean(float chance) Returns true if a random value between 0 and 1 is less than the specified value.- Parameters:
chance- a float between 0.0 and 1.0; higher values are more likely to result in true- Returns:
- a boolean selected with the given
chanceof being true
-
nextSign
public int nextSign()Returns -1 or 1, randomly.- Returns:
- -1 or 1, selected with approximately equal likelihood
-
nextTriangular
public float nextTriangular()Returns a triangularly distributed random number between -1.0 (exclusive) and 1.0 (exclusive), where values around zero are more likely. Advances the state twice.This is an optimized version of
nextTriangular(-1, 1, 0) -
nextTriangular
public float nextTriangular(float max) Returns a triangularly distributed random number between-max(exclusive) andmax(exclusive), where values around zero are more likely. Advances the state twice.This is an optimized version of
nextTriangular(-max, max, 0)- Parameters:
max- the upper limit
-
nextTriangular
public float nextTriangular(float min, float max) Returns a triangularly distributed random number betweenmin(inclusive) andmax(exclusive), where themodeargument defaults to the midpoint between the bounds, giving a symmetric distribution. Advances the state once.This method is equivalent to
nextTriangular(min, max, (min + max) * 0.5f)- Parameters:
min- the lower limitmax- the upper limit
-
nextTriangular
public float nextTriangular(float min, float max, float mode) Returns a triangularly distributed random number betweenmin(inclusive) andmax(exclusive), where values aroundmodeare more likely. Advances the state once.- Parameters:
min- the lower limitmax- the upper limitmode- the point around which the values are more likely
-
minIntOf
public int minIntOf(int innerBound, int outerBound, int trials) Returns the minimum result oftrialscalls tonextSignedInt(int, int)using the giveninnerBoundandouterBound. The innerBound is inclusive; the outerBound is exclusive. The higher trials is, the lower the average value this returns.- Parameters:
innerBound- the inner inclusive bound; may be positive or negativeouterBound- the outer exclusive bound; may be positive or negativetrials- how many random numbers to acquire and compare- Returns:
- the lowest random number between innerBound (inclusive) and outerBound (exclusive) this found
-
maxIntOf
public int maxIntOf(int innerBound, int outerBound, int trials) Returns the maximum result oftrialscalls tonextSignedInt(int, int)using the giveninnerBoundandouterBound. The innerBound is inclusive; the outerBound is exclusive. The higher trials is, the higher the average value this returns.- Parameters:
innerBound- the inner inclusive bound; may be positive or negativeouterBound- the outer exclusive bound; may be positive or negativetrials- how many random numbers to acquire and compare- Returns:
- the highest random number between innerBound (inclusive) and outerBound (exclusive) this found
-
minLongOf
public long minLongOf(long innerBound, long outerBound, int trials) Returns the minimum result oftrialscalls tonextSignedLong(long, long)using the giveninnerBoundandouterBound. The innerBound is inclusive; the outerBound is exclusive. The higher trials is, the lower the average value this returns.- Parameters:
innerBound- the inner inclusive bound; may be positive or negativeouterBound- the outer exclusive bound; may be positive or negativetrials- how many random numbers to acquire and compare- Returns:
- the lowest random number between innerBound (inclusive) and outerBound (exclusive) this found
-
maxLongOf
public long maxLongOf(long innerBound, long outerBound, int trials) Returns the maximum result oftrialscalls tonextSignedLong(long, long)using the giveninnerBoundandouterBound. The innerBound is inclusive; the outerBound is exclusive. The higher trials is, the higher the average value this returns.- Parameters:
innerBound- the inner inclusive bound; may be positive or negativeouterBound- the outer exclusive bound; may be positive or negativetrials- how many random numbers to acquire and compare- Returns:
- the highest random number between innerBound (inclusive) and outerBound (exclusive) this found
-
minDoubleOf
public double minDoubleOf(double innerBound, double outerBound, int trials) Returns the minimum result oftrialscalls tonextDouble(double, double)using the giveninnerBoundandouterBound. The innerBound is inclusive; the outerBound is exclusive. The higher trials is, the lower the average value this returns.- Parameters:
innerBound- the inner inclusive bound; may be positive or negativeouterBound- the outer exclusive bound; may be positive or negativetrials- how many random numbers to acquire and compare- Returns:
- the lowest random number between innerBound (inclusive) and outerBound (exclusive) this found
-
maxDoubleOf
public double maxDoubleOf(double innerBound, double outerBound, int trials) Returns the maximum result oftrialscalls tonextDouble(double, double)using the giveninnerBoundandouterBound. The innerBound is inclusive; the outerBound is exclusive. The higher trials is, the higher the average value this returns.- Parameters:
innerBound- the inner inclusive bound; may be positive or negativeouterBound- the outer exclusive bound; may be positive or negativetrials- how many random numbers to acquire and compare- Returns:
- the highest random number between innerBound (inclusive) and outerBound (exclusive) this found
-
minFloatOf
public float minFloatOf(float innerBound, float outerBound, int trials) Returns the minimum result oftrialscalls tonextFloat(float, float)using the giveninnerBoundandouterBound. The innerBound is inclusive; the outerBound is exclusive. The higher trials is, the lower the average value this returns.- Parameters:
innerBound- the inner inclusive bound; may be positive or negativeouterBound- the outer exclusive bound; may be positive or negativetrials- how many random numbers to acquire and compare- Returns:
- the lowest random number between innerBound (inclusive) and outerBound (exclusive) this found
-
maxFloatOf
public float maxFloatOf(float innerBound, float outerBound, int trials) Returns the maximum result oftrialscalls tonextFloat(float, float)using the giveninnerBoundandouterBound. The innerBound is inclusive; the outerBound is exclusive. The higher trials is, the higher the average value this returns.- Parameters:
innerBound- the inner inclusive bound; may be positive or negativeouterBound- the outer exclusive bound; may be positive or negativetrials- how many random numbers to acquire and compare- Returns:
- the highest random number between innerBound (inclusive) and outerBound (exclusive) this found
-
randomElement
public <T> T randomElement(T[] array) Gets a randomly-selected item from the given array, which must be non-null and non-empty- Type Parameters:
T- any reference type- Parameters:
array- a non-null, non-empty array ofTitems- Returns:
- a random item from
array - Throws:
NullPointerException- if array is nullIndexOutOfBoundsException- if array is empty
-
randomElement
Gets a randomly selected item from the given List, such as an ArrayList. If the List is empty, this throws an IndexOutOfBoundsException.- Type Parameters:
T- the type of items- Parameters:
list- a non-empty implementation of List, such as ArrayList- Returns:
- a randomly-selected item from list
-
shuffle
public void shuffle(int[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- an int array; must be non-null
-
shuffle
public void shuffle(int[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- an int array; must be non-nulloffset- the index of the first element of the array that can be shuffledlength- the length of the section to shuffle
-
shuffle
public void shuffle(long[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- a long array; must be non-null
-
shuffle
public void shuffle(long[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- a long array; must be non-nulloffset- the index of the first element of the array that can be shuffledlength- the length of the section to shuffle
-
shuffle
public void shuffle(float[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- a float array; must be non-null
-
shuffle
public void shuffle(float[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- a float array; must be non-nulloffset- the index of the first element of the array that can be shuffledlength- the length of the section to shuffle
-
shuffle
public void shuffle(char[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- a char array; must be non-null
-
shuffle
public void shuffle(char[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- a char array; must be non-nulloffset- the index of the first element of the array that can be shuffledlength- the length of the section to shuffle
-
shuffle
public void shuffle(byte[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- a byte array; must be non-null
-
shuffle
public void shuffle(byte[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- a byte array; must be non-nulloffset- the index of the first element of the array that can be shuffledlength- the length of the section to shuffle
-
shuffle
public void shuffle(double[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- a double array; must be non-null
-
shuffle
public void shuffle(double[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- a double array; must be non-nulloffset- the index of the first element of the array that can be shuffledlength- the length of the section to shuffle
-
shuffle
public void shuffle(short[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- a short array; must be non-null
-
shuffle
public void shuffle(short[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- a short array; must be non-nulloffset- the index of the first element of the array that can be shuffledlength- the length of the section to shuffle
-
shuffle
public void shuffle(boolean[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- a boolean array; must be non-null
-
shuffle
public void shuffle(boolean[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- a boolean array; must be non-nulloffset- the index of the first element of the array that can be shuffledlength- the length of the section to shuffle
-
shuffle
public <T> void shuffle(T[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- an array of some reference type; must be non-null but may contain null items
-
shuffle
public <T> void shuffle(T[] items, int offset, int length) Shuffles a section of the given array in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- an array of some reference type; must be non-null but may contain null itemsoffset- the index of the first element of the array that can be shuffledlength- the length of the section to shuffle
-
shuffle
Shuffles the given List in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- a List of some typeT; must be non-null but may contain null items
-
shuffle
Shuffles a section of the given List in-place pseudo-randomly, using this to determine how to shuffle.- Parameters:
items- a List of some typeT; must be non-null but may contain null itemsoffset- the index of the first element of the array that can be shuffledlength- the length of the section to shuffle
-
stringSerialize
Serializes the current state of this EnhancedRandom to a String that can be used bystringDeserialize(String)to load this state at another time. This always usesBase.BASE16for its conversions.- Returns:
- a String storing all data from the EnhancedRandom part of this generator
-
stringSerialize
Serializes the current state of this EnhancedRandom to a String that can be used bystringDeserialize(String)to load this state at another time. May use anyBase;Base.BASE10andBase.BASE16are the most intuitive, butBase.SIMPLE64and especiallyBase.BASE90will be more compact.- Parameters:
base- which Base to use, from the "digital" library, such asBase.BASE10- Returns:
- a String storing all data from the EnhancedRandom part of this generator
-
appendSerialized
Serializes the current state of this EnhancedRandom and appends it to an Appendable CharSequence (such as a StringBuilder), which may be used bystringDeserialize(String)to load this state at another time. Always usesbase 16.- Type Parameters:
T- any type that is both a CharSequence and an Appendable, such as StringBuilder, StringBuffer, or CharBuffer- Parameters:
sb- an Appendable CharSequence that will be modified- Returns:
sb, for chaining
-
appendSerialized
public <T extends CharSequence & Appendable> T appendSerialized(T sb, com.github.tommyettinger.digital.Base base) Serializes the current state of this EnhancedRandom and appends it to an Appendable CharSequence (such as a StringBuilder), which may be used bystringDeserialize(String)to load this state at another time. May use anyBase;Base.BASE10andBase.BASE16are the most intuitive, butBase.SIMPLE64and especiallyBase.BASE90will be more compact.- Type Parameters:
T- any type that is both a CharSequence and an Appendable, such as StringBuilder, StringBuffer, or CharBuffer- Parameters:
sb- an Appendable CharSequence that will be modifiedbase- which Base to use, from the "digital" library, such asBase.BASE10- Returns:
sb, for chaining
-
stringDeserialize
Given a String in the format produced bystringSerialize(), this will attempt to set this EnhancedRandom object to match the state in the serialized data. This only works if this EnhancedRandom is the same implementation that was serialized. Always usesBase.BASE16. Returns this EnhancedRandom, after possibly changing its state.- Parameters:
data- a String probably produced bystringSerialize()- Returns:
- this, after setting its state
- See Also:
-
stringDeserialize
Given a String in the format produced bystringSerialize(Base), and the sameBaseused by the serialization, this will attempt to set this EnhancedRandom object to match the state in the serialized data. This only works if this EnhancedRandom is the same implementation that was serialized, and also needs the Bases to be identical. Returns this EnhancedRandom, after possibly changing its state.- Parameters:
data- a String probably produced bystringSerialize(Base)base- which Base to use, from the "digital" library, such asBase.BASE10- Returns:
- this, after setting its state
- See Also:
-
writeExternal
The object implements the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, and arrays.- Specified by:
writeExternalin interfaceExternalizable- Parameters:
out- the stream to write the object to- Throws:
IOException- Includes any I/O exceptions that may occur
-
readExternal
The object implements the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays. The readExternal method must read the values in the same sequence and with the same types as were written by writeExternal.- Specified by:
readExternalin interfaceExternalizable- Parameters:
in- the stream to read data from in order to restore the object- Throws:
IOException- if I/O errors occurClassNotFoundException
-