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
-
Constructor Summary
ConstructorDescriptionCreates a new LaserRandom.LaserRandom
(long seed) Creates a new LaserRandom using a singlelong
seed; the stream depends on whether the seed is even or odd.LaserRandom
(long seedA, long seedB) Creates a new LaserRandom usingseedA
exactly to set stateA (as withsetStateA(long)
,, and usingseedB
to 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 newLaserRandom
with 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.boolean
long
getSelectedState
(int selection) Gets a selected state value from this LaserRandom.long
Get the "A" part of the internal state as a long.long
Get the "B" part of the internal state as a long.int
LaserRandom has two possible states, bothlong
.long
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.getTag()
Gets the tag used to identify this type of EnhancedRandom, as a String.int
next
(int bits) Generates the next pseudorandom number with a specific maximum size in bits (not a max number).boolean
Returns the next pseudorandom, uniformly distributedboolean
value from this random number generator's sequence.boolean
nextBoolean
(float chance) Returns true if a random value between 0 and 1 is less than the specified value.void
nextBytes
(byte[] bytes) Generates random bytes and places them into a user-supplied byte array.double
Returns the next pseudorandom, uniformly distributeddouble
value between0.0
(inclusive) and1.0
(exclusive) from this random number generator's sequence.double
nextDouble
(double outerBound) Gets a pseudo-random double between 0 (inclusive) andouterBound
(exclusive).double
nextDouble
(double innerBound, double outerBound) Gets a pseudo-random double betweeninnerBound
(inclusive) andouterBound
(exclusive).float
Returns the next pseudorandom, uniformly distributedfloat
value between0.0
(inclusive) and1.0
(exclusive) from this random number generator's sequence.float
nextFloat
(float outerBound) Gets a pseudo-random float between 0 (inclusive) andouterBound
(exclusive).float
nextFloat
(float innerBound, float outerBound) Gets a pseudo-random float betweeninnerBound
(inclusive) andouterBound
(exclusive).double
Returns the next pseudorandom, Gaussian ("normally") distributeddouble
value with mean0.0
and standard deviation1.0
from this random number generator's sequence.double
This is just likenextDouble()
, returning a double between 0 and 1, except that it is inclusive on both 0.0 and 1.0.double
nextInclusiveDouble
(double outerBound) Just likenextDouble(double)
, but this is inclusive on both 0.0 andouterBound
.double
nextInclusiveDouble
(double innerBound, double outerBound) float
This is just likenextFloat()
, returning a float between 0 and 1, except that it is inclusive on both 0.0 and 1.0.float
nextInclusiveFloat
(float outerBound) Just likenextFloat(float)
, but this is inclusive on both 0.0 andouterBound
.float
nextInclusiveFloat
(float innerBound, float outerBound) int
nextInt()
Returns the next pseudorandom, uniformly distributedint
value from this random number generator's sequence.int
nextInt
(int bound) Returns a pseudorandom, uniformly distributedint
value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.int
nextInt
(int innerBound, int outerBound) Returns a pseudorandom, uniformly distributedint
value between the specifiedinnerBound
(inclusive) and the specifiedouterBound
(exclusive).long
nextLong()
Returns the next pseudorandom, uniformly distributedlong
value from this random number generator's sequence.long
nextLong
(long bound) Returns a pseudorandom, uniformly distributedlong
value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.long
nextLong
(long inner, long outer) Returns a pseudorandom, uniformly distributedlong
value between the specifiedinnerBound
(inclusive) and the specifiedouterBound
(exclusive).int
nextSign()
Returns -1 or 1, randomly.int
nextSignedInt
(int outerBound) Returns a pseudorandom, uniformly distributedint
value between an inner bound of 0 (inclusive) and the specifiedouterBound
(exclusive).int
nextSignedInt
(int innerBound, int outerBound) Returns a pseudorandom, uniformly distributedint
value between the specifiedinnerBound
(inclusive) and the specifiedouterBound
(exclusive).long
nextSignedLong
(long outerBound) Returns a pseudorandom, uniformly distributedlong
value between an inner bound of 0 (inclusive) and the specifiedouterBound
(exclusive).long
nextSignedLong
(long inner, long outer) Returns a pseudorandom, uniformly distributedlong
value between the specifiedinnerBound
(inclusive) and the specifiedouterBound
(exclusive).float
Returns a triangularly distributed random number between -1.0 (exclusive) and 1.0 (exclusive), where values around zero are more likely.float
nextTriangular
(float max) Returns a triangularly distributed random number between-max
(exclusive) andmax
(exclusive), where values around zero are more likely.float
nextTriangular
(float min, float max) Returns a triangularly distributed random number betweenmin
(inclusive) andmax
(exclusive), where themode
argument defaults to the midpoint between the bounds, giving a symmetric distribution.float
nextTriangular
(float min, float max, float mode) Returns a triangularly distributed random number betweenmin
(inclusive) andmax
(exclusive), where values aroundmode
are more likely.int
nextUnsignedInt
(int bound) Returns a pseudorandom, uniformly distributedint
value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.long
Optional; moves the state to its previous value and returns the previous long that would have been produced byEnhancedRandom.nextLong()
.<T> T
randomElement
(T[] array) Gets a randomly-selected item from the given array, which must be non-null and non-emptyvoid
setSeed
(long seed) Sets the seed of this random number generator using a singlelong
seed.void
setSelectedState
(int selection, long value) Sets a selected state value to the given longvalue
.void
setState
(long stateA, long stateB) Sets both parts of the internal state with one call;stateA
is used verbatim, butstateB
has its least significant bit ignored and always overwritten with a '1' bit (meaning stateB will always be odd).void
setStateA
(long stateA) Set the "A" part of the internal state with a long.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).void
shuffle
(boolean[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.void
shuffle
(byte[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.void
shuffle
(char[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.void
shuffle
(double[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.void
shuffle
(float[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.void
shuffle
(int[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.void
shuffle
(long[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.void
shuffle
(short[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.<T> void
shuffle
(T[] items) Shuffles the given array in-place pseudo-randomly, using this to determine how to shuffle.long
skip
(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
areEqual, fixGamma, maxDoubleOf, maxFloatOf, maxIntOf, maxLongOf, minDoubleOf, minFloatOf, minIntOf, minLongOf, nextExclusiveDouble, nextExclusiveDouble, nextExclusiveDouble, nextExclusiveDoubleEquidistant, nextExclusiveFloat, nextExclusiveFloat, nextExclusiveFloat, nextExclusiveFloatEquidistant, nextExclusiveSignedDouble, nextExclusiveSignedFloat, nextGaussian, previousInt, probit, randomElement, readExternal, seedFromMath, setState, setState, setState, setState, setState, setWith, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, stringDeserialize, stringDeserialize, stringSerialize, stringSerialize, writeExternal
Methods inherited from class java.util.Random
doubles, doubles, doubles, doubles, ints, ints, ints, ints, longs, longs, longs, longs
Methods inherited from class java.lang.Object
clone, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
Methods inherited from interface java.util.random.RandomGenerator
isDeprecated, nextExponential
-
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 singlelong
seed; 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 usingseedA
exactly to set stateA (as withsetStateA(long)
,, and usingseedB
to 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:EnhancedRandom
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.- Specified by:
getTag
in classEnhancedRandom
- Returns:
- a unique String identifier for this type of EnhancedRandom; usually 4 chars long.
-
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:
getStateCount
in 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;stateA
is used verbatim, butstateB
has 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, keepingstateB
an odd number should be optimal.- Overrides:
setState
in 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:
getSelectedState
in 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:
setSelectedState
in 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 singlelong
seed. The general contract ofsetSeed
is 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 argumentseed
as a seed.The implementation of
setSeed
by classLaserRandom
uses 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:
setSeed
in 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)
. Forbits
values 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. Ifbits
is 31, this can return any non-negativeint
; note thatnextInt(1 << 31)
won't behave this way because1 << 31
is negative. Ifbits
is 32 (or 0), this can return anyint
.The general contract of
next
is that it returns anint
value and if the argumentbits
is between1
and32
(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 be0
or1
.- Overrides:
next
in 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:
nextBytes
in interfaceRandomGenerator
- Overrides:
nextBytes
in 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 distributedint
value from this random number generator's sequence. The general contract ofnextInt
is that oneint
value is pseudorandomly generated and returned. All 232 possibleint
values are produced with (approximately) equal probability.- Specified by:
nextInt
in interfaceRandomGenerator
- Overrides:
nextInt
in classEnhancedRandom
- Returns:
- the next pseudorandom, uniformly distributed
int
value from this random number generator's sequence
-
nextInt
public int nextInt(int bound) Returns a pseudorandom, uniformly distributedint
value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract ofnextInt
is that oneint
value in the specified range is pseudorandomly generated and returned. Allbound
possibleint
values 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:
nextInt
in interfaceRandomGenerator
- Overrides:
nextInt
in classEnhancedRandom
- Parameters:
bound
- the upper bound (exclusive). If negative or 0, this always returns 0.- Returns:
- the next pseudorandom, uniformly distributed
int
value between zero (inclusive) andbound
(exclusive) from this random number generator's sequence
-
nextUnsignedInt
public int nextUnsignedInt(int bound) Returns a pseudorandom, uniformly distributedint
value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract ofnextInt
is that oneint
value in the specified range is pseudorandomly generated and returned. Allbound
possibleint
values 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:
nextUnsignedInt
in classEnhancedRandom
- Parameters:
bound
- the upper bound (exclusive). If negative or 0, this always returns 0.- Returns:
- the next pseudorandom, uniformly distributed
int
value between zero (inclusive) andbound
(exclusive) from this random number generator's sequence
-
nextSignedInt
public int nextSignedInt(int outerBound) Returns a pseudorandom, uniformly distributedint
value 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:
nextSignedInt
in 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 distributedint
value between the specifiedinnerBound
(inclusive) and the specifiedouterBound
(exclusive). IfouterBound
is 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:
nextInt
in interfaceRandomGenerator
- Overrides:
nextInt
in 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 distributedint
value 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:
nextSignedInt
in 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 distributedlong
value from this random number generator's sequence. The general contract ofnextLong
is that onelong
value is pseudorandomly generated and returned.
An individualLaserRNG
can't return all 18-quintillion possiblelong
values, but the full set of 9-quintillion possible random number streams that this class can produce will, as a whole, produce alllong
values with equal likelihood.- Specified by:
nextLong
in interfaceRandomGenerator
- Specified by:
nextLong
in classEnhancedRandom
- Returns:
- the next pseudorandom, uniformly distributed
long
value from this random number generator's sequence
-
nextLong
public long nextLong(long bound) Returns a pseudorandom, uniformly distributedlong
value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract ofnextLong
is that onelong
value in the specified range is pseudorandomly generated and returned. Allbound
possiblelong
values 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 whenbound
is very large. This will also advance the state ifbound
is 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:
nextLong
in interfaceRandomGenerator
- Overrides:
nextLong
in classEnhancedRandom
- Parameters:
bound
- the upper bound (exclusive). If negative or 0, this always returns 0.- Returns:
- the next pseudorandom, uniformly distributed
long
value between zero (inclusive) andbound
(exclusive) from this random number generator's sequence - See Also:
-
nextSignedLong
public long nextSignedLong(long outerBound) Returns a pseudorandom, uniformly distributedlong
value 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 whenbound
is very large. This method should be about as fast asnextLong(long)
, unlike the speed difference betweennextInt(int)
andnextSignedInt(int)
.- Overrides:
nextSignedLong
in 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 distributedlong
value between the specifiedinnerBound
(inclusive) and the specifiedouterBound
(exclusive). IfouterBound
is 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:
nextLong
in interfaceRandomGenerator
- Overrides:
nextLong
in 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 distributedlong
value 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:
nextSignedLong
in 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 distributedboolean
value from this random number generator's sequence. The general contract ofnextBoolean
is that oneboolean
value is pseudorandomly generated and returned. The valuestrue
andfalse
are produced with (approximately) equal probability.- Specified by:
nextBoolean
in interfaceRandomGenerator
- Overrides:
nextBoolean
in classEnhancedRandom
- Returns:
- the next pseudorandom, uniformly distributed
boolean
value from this random number generator's sequence
-
nextFloat
public float nextFloat()Returns the next pseudorandom, uniformly distributedfloat
value between0.0
(inclusive) and1.0
(exclusive) from this random number generator's sequence.The general contract of
nextFloat
is that onefloat
value, chosen (approximately) uniformly from the range0.0f
(inclusive) to1.0f
(exclusive), is pseudorandomly generated and returned. All 224 possiblefloat
values 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
float
values from the stated range with perfect uniformity.- Specified by:
nextFloat
in interfaceRandomGenerator
- Overrides:
nextFloat
in classEnhancedRandom
- Returns:
- the next pseudorandom, uniformly distributed
float
value between0.0
and1.0
from 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:
nextFloat
in interfaceRandomGenerator
- Overrides:
nextFloat
in 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:
nextFloat
in interfaceRandomGenerator
- Overrides:
nextFloat
in 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 distributeddouble
value between0.0
(inclusive) and1.0
(exclusive) from this random number generator's sequence.The general contract of
nextDouble
is that onedouble
value, 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
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 choosedouble
values from the stated range with perfect uniformity.- Specified by:
nextDouble
in interfaceRandomGenerator
- Overrides:
nextDouble
in classEnhancedRandom
- Returns:
- the next pseudorandom, uniformly distributed
double
value between0.0
and1.0
from 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:
nextDouble
in interfaceRandomGenerator
- Overrides:
nextDouble
in 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:
nextDouble
in interfaceRandomGenerator
- Overrides:
nextDouble
in 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:
nextInclusiveDouble
in 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:
nextInclusiveDouble
in 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 bothinnerBound
andouterBound
. 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:
nextInclusiveDouble
in 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:
nextInclusiveFloat
in 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:
nextInclusiveFloat
in 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 bothinnerBound
andouterBound
. 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:
nextInclusiveFloat
in 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") distributeddouble
value with mean0.0
and standard deviation1.0
from this random number generator's sequence.The general contract of
nextGaussian
is that onedouble
value, chosen from (approximately) the usual normal distribution with mean0.0
and 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:
nextGaussian
in interfaceRandomGenerator
- Overrides:
nextGaussian
in classEnhancedRandom
- Returns:
- the next pseudorandom, Gaussian ("normally") distributed
double
value with mean0.0
and standard deviation1.0
from 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:
skip
in 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
advance
numbers
-
previousLong
public long previousLong()Description copied from class:EnhancedRandom
Optional; 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 generateint
results typically producelong
values 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 producelong
values usually don't need to implementEnhancedRandom.previousInt()
, but those that produceint
usually 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:
previousLong
in classEnhancedRandom
- Returns:
- the previous number this would have produced with
EnhancedRandom.nextLong()
-
copy
Creates a newLaserRandom
with 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 theRandom
parent class, so if you call methods that are only implemented by Random and not LaserRandom, the results may differ.- Specified by:
copy
in 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:
nextBoolean
in 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
chance
of being true
-
nextSign
public int nextSign()Returns -1 or 1, randomly.- Overrides:
nextSign
in 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:
nextTriangular
in 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:
nextTriangular
in 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 themode
argument 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:
nextTriangular
in 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 aroundmode
are more likely. Advances the state once.- Overrides:
nextTriangular
in 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:
randomElement
in classEnhancedRandom
- Type Parameters:
T
- any reference type- Parameters:
array
- a non-null, non-empty array ofT
items- 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:
shuffle
in 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:
shuffle
in 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:
shuffle
in 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:
shuffle
in 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:
shuffle
in 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:
shuffle
in 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:
shuffle
in 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:
shuffle
in 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:
shuffle
in 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.
-