Class LaserRandom
- All Implemented Interfaces:
Externalizable,Serializable,RandomGenerator
Random. This allows many different random number
streams that don't overlap, and offers a more substantial API for commonly-used functions. This is not a
cryptographic random number generator, and should not be used in place of one.
This fills in much of the functionality of MathUtils in libGDX, though with all code as instance methods instead of static methods, and some things renamed (randomTriangular() became
nextTriangular(),
for instance, and random() became nextFloat()). It also supplies some rare and sometimes-useful
code: skip(long) allows "fast-forward" and "rewind" along with previousLong() to simply
go back one step, you can get and set the exact state with getStateA(), getStateB(),
setStateA(long), setStateB(long), and setState(long, long) (which is useful
if you want to save a LaserRandom and reload it later), and there's bounded int and long generators which
can use a negative number for their exclusive outer bound (nextSignedInt(int) and
nextSignedLong(long), plus overloads that take an inner bound). There's float and double
generators that are inclusive on both ends (nextInclusiveFloat(), and
nextInclusiveDouble(). There's nextGaussian(), which is implemented differently from
java.util.Random and always advances the state once. This implements all optional methods in
EnhancedRandom, and implements almost all EnhancedRandom methods explicitly, which allows LaserRandom to
be copied more easily without depending on juniper (see below).
Every method defined in this class advances the state by the same amount unless otherwise documented (only
nextTriangular() and nextTriangular(float) advance the state twice). The state can
advance 2 to the 64 times before the sequence of random numbers repeats, which would take a few years of
continuous generation. There are also 2 to the 63 possible sequences this can produce; you can tell which
one you're using with getStream(). Note, Random can only advance 2 to the 48 times, which
takes under half a day to make it repeat on recent laptop hardware while also analyzing the numbers for
statistical issues. This generator is more comparable to SplittableRandom, introduced in JDK 8 but not
available in Android (even with desugaring) or GWT currently. SplittableRandom also can produce 2 to the
64 numbers before repeating the sequence, and also has 2 to the 63 streams, but it will always produce
each possible long value exactly once over the course of that sequence. Each of LaserRandom's streams
produces a different sequence of numbers with a different set of numbers it omits and a different set of
numbers it produces more than once; each of SplittableRandom's streams simply rearranges the order of all
possible longs. Though it might seem like an issue that a LaserRandom stream has gaps in its possible
output, if you appended all 2 to the 63 possible LaserRandom streams in full, the gargantuan result would
include all longs equally often. So, if the stream is selected effectively at random, then the subset of
that stream that actually gets used should be fair (and it's very unlikely that any usage will need a full
stream of over 18 quintillion pseudo-random longs). It is strongly recommended that you use very different
numbers when creating many LaserRandom objects with similar states, because there is a noticeable
correlation between, for instance, a grid of LaserRandom objects initialized with stateA drawn from the
odd numbers 1 through 101, and stateB drawn from another odd number 1 through 101. Using
setSeed(long) essentially eliminates this risk, so it's a good idea to seed this with one long.
If statistical quality is a concern, don't use
Random, since the aforementioned
analysis finds statistical failures in about a minute when checking about 16GB of output; this class can
produce 64TB of random output without a tool like PractRand finding any failures (sometimes it can't find
any minor anomaly over several days of testing). RandomXS128 has some flaws, though they are not nearly as
severe as Random's; mostly they are limited to a particular kind of failure affecting the least
significant bits (the technical name for the test it fails is a "binary matrix rank" test, which a wide
variety of related generators can fail if they don't adequately randomize their outputs). RandomXS128's
flaws would be permissible if it was faster than any competitors, but it isn't, and there have been two
improved relatives of its algorithm published since it was created. Both of these improvements,
xoroshiro128** and xoshiro256**, are slower when implemented in Java than LaserRandom (also when all are
implemented in C and compiled with GCC or Clang, typically). There are also some concerns about specific
failure cases when the output of xoroshiro128** or xoshiro256** is multiplied by any of quadrillions of
constants and tested after that multiplication (see M.E. O'Neill's dissection of xoshiro256**
here). Xoshiro256**, like
LaserRandom, can't be reliably initialized using nearby values for its state variables, and does much
better if you use its setSeed(long) method. We do implement Xoshiro256** here, because it provides
4-dimensional equidistribution, and that is hard to find.
You can copy this class independently of the library it's part of; it's meant as a general replacement for Random and also RandomXS128. LaserRandom is generally faster than RandomXS128, and can be over 3x faster when running on OpenJ9 (generating over 3 billion random long values per second). If you copy this, the only step you probably need to do is to remove
extends EnhancedRandom from the class, since
almost all of EnhancedRandom consists of either parent methods that this overrides explicitly, or to
provide a common interface for pseudo-random number generators on the JVM. This class avoids using the
Override annotation specifically because copying the class and removing the EnhancedRandom implementation
would cause compile errors if Override annotations were present. If you do keep this class implementing
EnhancedRandom, then that permits some extra methods to come in via default implementations, like
nextExclusiveFloat() (which uses the BitConversion class here from digital), minIntOf(), maxLongOf(), etc.
You may want to compare this class with TricycleRandom and FourWheelRandom in the same package; both of those have a larger state size (and should usually have a larger period), are usually faster, and also implement all of EnhancedRandom (except for
skip(long)), but they do even less randomizing for
the first result they return, so if the seeding has a pattern, then the start of their sequences will
have patterns. These patterns are less obvious but do persist in LaserRandom, and don't persist in
TricycleRandom or FourWheelRandom over a long run. All generators here do well when using
setSeed(long) to set the full state.
Pew pew! Lasers!
- 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 -
Field Summary
Fields -
Constructor Summary
ConstructorsConstructorDescriptionCreates a new LaserRandom.LaserRandom(long seed) Creates a new LaserRandom using a singlelongseed; the stream depends on whether the seed is even or odd.LaserRandom(long seedA, long seedB) Creates a new LaserRandom usingseedAexactly to set stateA (as withsetStateA(long),, and usingseedBto set stateB as withsetStateB(long)(meaning seedB will be used exactly if odd, otherwise it will have 1 added to it and then used). -
Method Summary
Modifier and TypeMethodDescriptioncopy()Creates a newLaserRandomwith identical states to this one, so if the same LaserRandom methods are called on this object and its copy (in the same order), the same outputs will be produced.boolean2 to the 64.longgetSelectedState(int selection) Gets a selected state value from this LaserRandom.longGet the "A" part of the internal state as a long.longGet the "B" part of the internal state as a long.intLaserRandom has two possible states, bothlong.longGets a long that identifies which stream of numbers this generator is producing; this stream identifier is always an odd long and won't change by generating numbers.getTag()Gets the tag used to identify this type of EnhancedRandom, as a String.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).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.floatReturns the next pseudorandom, Gaussian ("normally") distributedfloatvalue with mean0.0and standard deviation1.0from 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).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.longOptional; moves the state to its previous value and returns the previous long that would have been produced byEnhancedRandom.nextLong().<T> TrandomElement(T[] array) Gets a randomly-selected item from the given array, which must be non-null and non-emptyvoidsetSeed(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 stateA, long stateB) Sets both parts of the internal state with one call;stateAis used verbatim, butstateBhas its least significant bit ignored and always overwritten with a '1' bit (meaning stateB will always be odd).voidsetStateA(long stateA) Set the "A" part of the internal state with a long.voidsetStateB(long stateB) Set the "B" part of the internal state with a long; the least significant bit is ignored (will always be odd).voidshuffle(boolean[] items) Shuffles 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(char[] items) Shuffles 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(float[] items) Shuffles 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(long[] items) Shuffles 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.<T> voidshuffle(T[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.longskip(long advance) Advances or rolls back theLaserRandom' state without actually generating each number.toString()This String conversion uses base-10 numbers for the states, unlike all other EnhancedRandom implementations, which use base-16.Methods inherited from class com.github.tommyettinger.random.EnhancedRandom
appendSerialized, appendSerialized, areEqual, fixGamma, fixGamma, lcm, mainlyGeneratesInt, maxDoubleOf, maxFloatOf, maxIntOf, maxLongOf, minDoubleOf, minFloatOf, minIntOf, minLongOf, nextExclusiveDouble, nextExclusiveDouble, nextExclusiveDouble, nextExclusiveDoubleEquidistant, nextExclusiveFloat, nextExclusiveFloat, nextExclusiveFloat, nextExclusiveFloatEquidistant, nextExclusiveSignedDouble, nextExclusiveSignedFloat, nextExponential, nextGaussian, nextGaussianFloat, previousInt, probit, randomElement, rateGamma, readExternal, seedFromMath, setState, setState, setState, setState, setState, setState, setWith, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, stringDeserialize, stringDeserialize, stringSerialize, stringSerialize, writeExternalMethods 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, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface java.util.random.RandomGenerator
isDeprecated
-
Field Details
-
stateA
protected long stateACan be any long value. -
stateB
protected long stateBMust be odd.
-
-
Constructor Details
-
LaserRandom
public LaserRandom()Creates a new LaserRandom. This constructor sets the states of the random number generator to values very likely to be distinct from any other invocation of this constructor. -
LaserRandom
public LaserRandom(long seed) Creates a new LaserRandom using a singlelongseed; the stream depends on whether the seed is even or odd.- Parameters:
seed- the initial seed- See Also:
-
LaserRandom
public LaserRandom(long seedA, long seedB) Creates a new LaserRandom usingseedAexactly to set stateA (as withsetStateA(long),, and usingseedBto set stateB as withsetStateB(long)(meaning seedB will be used exactly if odd, otherwise it will have 1 added to it and then used).- Parameters:
seedA- any long; will be used exactly to set stateA as withsetStateA(long)seedB- any odd long will be used exactly to set stateB, otherwise, as withsetStateB(long), it will be made odd
-
-
Method Details
-
getTag
Description copied from class:EnhancedRandomGets 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.- Specified by:
getTagin classEnhancedRandom- Returns:
- a unique String identifier for this type of EnhancedRandom; usually 4 chars long.
-
getMinimumPeriod
2 to the 64.- Overrides:
getMinimumPeriodin classEnhancedRandom- Returns:
- 2 to the 64
-
getStateCount
public int getStateCount()LaserRandom has two possible states, bothlong. The second state (selection1) is always an odd number, and if anything tries to set an even number to that state, the actual state used will be one greater.- Overrides:
getStateCountin classEnhancedRandom- Returns:
- 2 (two)
-
getStateA
public long getStateA()Get the "A" part of the internal state as a long.- Returns:
- the current internal "A" state of this object.
-
setStateA
public void setStateA(long stateA) Set the "A" part of the internal state with a long.- Parameters:
stateA- a 64-bit long
-
getStateB
public long getStateB()Get the "B" part of the internal state as a long.- Returns:
- the current internal "B" state of this object.
-
setStateB
public void setStateB(long stateB) Set the "B" part of the internal state with a long; the least significant bit is ignored (will always be odd). That is, if stateB is odd, this uses it verbatim; if stateB is even, it adds 1 to it to make it odd.- Parameters:
stateB- a 64-bit long; the lowest bit will be ignored and the result always used as an odd number
-
setState
public void setState(long stateA, long stateB) Sets both parts of the internal state with one call;stateAis used verbatim, butstateBhas its least significant bit ignored and always overwritten with a '1' bit (meaning stateB will always be odd). You can use any long for stateA without it being changed, and can use any odd long for stateB without it being changed; as such, keepingstateBan odd number should be optimal.- Overrides:
setStatein classEnhancedRandom- Parameters:
stateA- a 64-bit longstateB- a 64-bit long; the lowest bit will be ignored and the result always used as an odd number
-
getSelectedState
public long getSelectedState(int selection) Gets a selected state value from this LaserRandom. If selection is an even number, this returns stateA, and if selection is odd, it returns stateB. This returns the exact value of the selected state.- Overrides:
getSelectedStatein classEnhancedRandom- Parameters:
selection- used to select which state variable to get (usually 0 or 1)- 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. If selection is an even number, this sets stateA to value as-is, and if selection is odd, this sets stateB to value made odd (that is, if value is even, it uses value + 1, otherwise it uses value).- Overrides:
setSelectedStatein classEnhancedRandom- Parameters:
selection- used to select which state variable to set (usually 0 or 1)value- the exact value to use for the selected state, if valid
-
setSeed
public void setSeed(long seed) Sets the seed of this random number generator using a singlelongseed. The general contract ofsetSeedis that it alters the state of this random number generator object so as to be in exactly the same state as if it had just been created with the argumentseedas a seed.The implementation of
setSeedby classLaserRandomuses all 64 bits of the given seed forsetStateA(long), and all but the least-significant bit of the seed forsetStateB(long)(the omitted bit is always set to 1 in stateB, meaning stateB is always odd).- Specified by:
setSeedin classEnhancedRandom- Parameters:
seed- the initial seed
-
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.- Overrides:
nextin classEnhancedRandom- Parameters:
bits- the amount of random bits to request, from 1 to 32- Returns:
- the next pseudorandom value from this random number generator's sequence
-
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 classEnhancedRandom- 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 classEnhancedRandom- 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.
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 classEnhancedRandom- 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).
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 this technique 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.- Overrides:
nextUnsignedIntin classEnhancedRandom- 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
-
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).- Overrides:
nextSignedIntin classEnhancedRandom- 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).- Specified by:
nextIntin interfaceRandomGenerator- Overrides:
nextIntin classEnhancedRandom- 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.- Overrides:
nextSignedIntin classEnhancedRandom- 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 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.
An individualLaserRNGcan't return all 18-quintillion possiblelongvalues, but the full set of 9-quintillion possible random number streams that this class can produce will, as a whole, produce alllongvalues with equal likelihood.- Specified by:
nextLongin interfaceRandomGenerator- Specified by:
nextLongin classEnhancedRandom- 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- Overrides:
nextLongin classEnhancedRandom- 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).- Overrides:
nextSignedLongin classEnhancedRandom- 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- Overrides:
nextLongin classEnhancedRandom- 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.- Overrides:
nextSignedLongin classEnhancedRandom- 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.- Specified by:
nextBooleanin interfaceRandomGenerator- Overrides:
nextBooleanin classEnhancedRandom- 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 hedge "approximately" is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choose
floatvalues from the stated range with perfect uniformity.- Specified by:
nextFloatin interfaceRandomGenerator- Overrides:
nextFloatin classEnhancedRandom- 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- Overrides:
nextFloatin classEnhancedRandom- 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- Overrides:
nextFloatin classEnhancedRandom- 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 hedge "approximately" is used in the foregoing description only because the
nextmethod is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choosedoublevalues from the stated range with perfect uniformity.- Specified by:
nextDoublein interfaceRandomGenerator- Overrides:
nextDoublein classEnhancedRandom- 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- Overrides:
nextDoublein classEnhancedRandom- 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- Overrides:
nextDoublein classEnhancedRandom- 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 extremely rarely, 0.000000000000011102230246251565% of the time if there is no bias in the generator, but it can happen. This usesnextLong(long)internally, so it may have some bias towards or against specific subtly-different results. Other generators here use BitConversion and a very different algorithm, but this avoids BitConversion so that it can be copied more easily.- Overrides:
nextInclusiveDoublein classEnhancedRandom- 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.- Overrides:
nextInclusiveDoublein classEnhancedRandom- 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.- Overrides:
nextInclusiveDoublein classEnhancedRandom- 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.00000596046412226771% of the time if there is no bias in the generator, but it can happen. This method has been tested by generating 268435456 (or 0x10000000) random ints withnextInt(int), and just before the end of that it had generated every one of the 16777217 roughly-equidistant floats this is able to produce. Not all seeds and streams are likely to accomplish that in the same time, or at all, depending on the generator.- Overrides:
nextInclusiveFloatin classEnhancedRandom- 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.- Overrides:
nextInclusiveFloatin classEnhancedRandom- 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.- Overrides:
nextInclusiveFloatin classEnhancedRandom- 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
-
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 uses an inverse transform sample method to generate its random values, using a method called probit(). The algorithm used was written by Peter John Acklam, and implemented by Sherali Karimov. Original source. Information on the algorithm. As this is written, it can return a maximum result of 8.209536145151493, and a minimum result of -38.5 . 38.5 only occurs 1 in every (2 to the 53) calls, on average, and all other results are between -8.209536145151493 and 8.209536145151493 . Note, this implementation is different from the one in EnhancedRandom only to permit copying this class more easily; EnhancedRandom normally uses another class, Ziggurat, to more efficiently generate normally-distributed doubles.
- Specified by:
nextGaussianin interfaceRandomGenerator- Overrides:
nextGaussianin classEnhancedRandom- Returns:
- the next pseudorandom, Gaussian ("normally") distributed
doublevalue with mean0.0and standard deviation1.0from this random number generator's sequence
-
nextGaussianFloat
public float nextGaussianFloat()Returns the next pseudorandom, Gaussian ("normally") distributedfloatvalue with mean0.0and standard deviation1.0from this random number generator's sequence.The implementation here was ported from code by Marc B. Reynolds and modified to only require one call to
nextLong().- Overrides:
nextGaussianFloatin classEnhancedRandom- Returns:
- the next pseudorandom, Gaussian ("normally") distributed
floatvalue with mean0.0and standard deviation1.0from this random number generator's sequence
-
skip
public long skip(long advance) Advances or rolls back theLaserRandom' 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().Note that none of the number-generating methods here advance state differently from
nextLong()except for the Stream APIs. This is somewhat unusual; in many generators, calls tonextInt(int)and similar bounded-range random generators can advance the state by a variable amount. Using a fixed advance permits this method and also allows guaranteeing the cycle length (also called period), but introduces a tiny amount of bias for some bounds (mostly very large ones).- Overrides:
skipin classEnhancedRandom- 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()Description copied from class:EnhancedRandomOptional; moves the state to its previous value and returns the previous long that would have been produced byEnhancedRandom.nextLong(). This can be equivalent to callingEnhancedRandom.skip(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 byEnhancedRandom.previousInt(), should be reversed. Generators that natively producelongvalues usually don't need to implementEnhancedRandom.previousInt(), 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 callsEnhancedRandom.skip(long)with -1L, and if skip() has not been implemented differently, then it will throw an UnsupportedOperationException.- Overrides:
previousLongin classEnhancedRandom- Returns:
- the previous number this would have produced with
EnhancedRandom.nextLong()
-
copy
Creates a newLaserRandomwith identical states to this one, so if the same LaserRandom 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 theRandomparent class, so if you call methods that are only implemented by Random and not LaserRandom, the results may differ.- Specified by:
copyin classEnhancedRandom- Returns:
- a deep copy of this LaserRandom.
-
getStream
public long getStream()Gets a long that identifies which stream of numbers this generator is producing; this stream identifier is always an odd long and won't change by generating numbers. It is determined at construction and will usually (not always) change ifsetStateA(long)orsetStateB(long)are called. Each stream is a probably-unique sequence of 2 to the 64 longs, where approximately 1/3 of all possible longs will not ever occur (while others occur twice or more), but this set of results is different for every stream. There are 2 to the 63 possible streams, one for every odd long.- Returns:
- an odd long that identifies which stream this LaserRandom is generating from
-
nextBoolean
public boolean nextBoolean(float chance) Returns true if a random value between 0 and 1 is less than the specified value.- Overrides:
nextBooleanin classEnhancedRandom- 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.- Overrides:
nextSignin classEnhancedRandom- 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
randomTriangular(-1, 1, 0)- Overrides:
nextTriangularin classEnhancedRandom
-
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
randomTriangular(-max, max, 0)- Overrides:
nextTriangularin classEnhancedRandom- 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 of
randomTriangular(min, max, (min + max) * 0.5f)- Overrides:
nextTriangularin classEnhancedRandom- 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.- Overrides:
nextTriangularin classEnhancedRandom- Parameters:
min- the lower limitmax- the upper limitmode- the point around which the values are more likely
-
randomElement
public <T> T randomElement(T[] array) Gets a randomly-selected item from the given array, which must be non-null and non-empty- Overrides:
randomElementin classEnhancedRandom- 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
-
shuffle
public void shuffle(int[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Overrides:
shufflein classEnhancedRandom- Parameters:
items- an int array; must be non-null
-
shuffle
public void shuffle(long[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Overrides:
shufflein classEnhancedRandom- Parameters:
items- a long array; must be non-null
-
shuffle
public void shuffle(float[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Overrides:
shufflein classEnhancedRandom- Parameters:
items- a float array; must be non-null
-
shuffle
public void shuffle(char[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Overrides:
shufflein classEnhancedRandom- Parameters:
items- a char array; must be non-null
-
shuffle
public void shuffle(byte[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Overrides:
shufflein classEnhancedRandom- Parameters:
items- a byte array; must be non-null
-
shuffle
public void shuffle(double[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Overrides:
shufflein classEnhancedRandom- Parameters:
items- a double array; must be non-null
-
shuffle
public void shuffle(short[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Overrides:
shufflein classEnhancedRandom- Parameters:
items- a short array; must be non-null
-
shuffle
public void shuffle(boolean[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Overrides:
shufflein classEnhancedRandom- Parameters:
items- a boolean array; must be non-null
-
shuffle
public <T> void shuffle(T[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.- Overrides:
shufflein classEnhancedRandom- Parameters:
items- an array of some reference type; must be non-null but may contain null items
-
equals
-
toString
This String conversion uses base-10 numbers for the states, unlike all other EnhancedRandom implementations, which use base-16. This is done here to avoid a dependency on Base, allowing this class to be copied more easily.
-