Package com.github.tommyettinger.random
Class CompositeWrapper
java.lang.Object
java.util.Random
com.github.tommyettinger.random.EnhancedRandom
com.github.tommyettinger.random.CompositeWrapper
- All Implemented Interfaces:
Externalizable,Serializable,RandomGenerator
A wrapper around two EnhancedRandom instances, usually with different algorithms, that runs both generators to
produce any output and XORs their outputs to get a result for any "core" methods used to implement the rest. This is
mostly useful to extend the period of a generator such as
There isn't as much point in using two generators with the same algorithm, because the period will be the same, nor any two generators with the same
When it comes to equidistribution, using an exactly-1D-equidistributed generator such as DistinctRandom or OrbitalRandom as a composite with a generator with no common factors in its period should guarantee the resulting composite is also exactly-1D-equidistributed. Any higher dimensionality of equidistribution won't be feasible here while still extending the period length.
Xoshiro256StarStarRandom, which already has a very
long period, by using it as a composite with another generator such as OrbitalRandom. These two are examples
because they each have guaranteed period lengths, and those periods share no common denominator (they are relatively
coprime). That makes their composite have a period equal to the product of their two periods, which is just less than
2 to the 384.
There isn't as much point in using two generators with the same algorithm, because the period will be the same, nor any two generators with the same
getMinimumPeriod(). As a rule of thumb, you should typically choose a
generator with a period that is a power of two for one generator, and a generator with an odd number for a period for
the other. DistinctRandom and OrbitalRandom have single periods that are powers of two, and all
LFSR-type generators, including LFSR64QuasiRandom but also Xoroshiro128StarStarRandom,
Xoshiro256StarStarRandom, and other xoroshiro/xoshiro generators, have odd-number periods. Generators that
incorporate a counter often guarantee a minimum period that is a multiple of a power of two, such as
FlowRandom, AceRandom and TraceRandom. Combining an AceRandom with a
Xoshiro256StarStarRandom is guaranteed a longer period than Xoshiro256StarStarRandom on its own, since
AceRandom has a period that is a multiple of (2 to the 64) and that shares no common factor with
Xoshiro256StarStarRandom's period, which is (2 to the 256) minus 1. It's theoretically possible that AceRandom has
only one cycle, which would have a period of (2 to the 320), but it's statistically incredibly unlikely. It's more
useful to measure the guaranteed minimum period, and in that respect, a composite of AceRandom with
Xoshiro256StarStarRandom has the same minimum period as a composite of DistinctRandom with Xoshiro256StarStarRandom.
When it comes to equidistribution, using an exactly-1D-equidistributed generator such as DistinctRandom or OrbitalRandom as a composite with a generator with no common factors in its period should guarantee the resulting composite is also exactly-1D-equidistributed. Any higher dimensionality of equidistribution won't be feasible here while still extending the period length.
- 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 randomly-seeded composite of anOrbitalRandomandXoshiro256StarStarRandom, with a guaranteed period of (2 to the 384) minus (2 to the 128).CompositeWrapper(long seed) Creates a seeded composite of anOrbitalRandomandXoshiro256StarStarRandom, with a guaranteed period of (2 to the 384) minus (2 to the 128).CompositeWrapper(long stateA, long stateB, long stateC, long stateD, long stateE, long stateF) Creates a seeded composite of anOrbitalRandomandXoshiro256StarStarRandom, with a guaranteed period of (2 to the 384) minus (2 to the 128).Creates a composite of the two given generators, if non-null. -
Method Summary
Modifier and TypeMethodDescription<T extends CharSequence & Appendable>
TappendSerialized(T sb, com.github.tommyettinger.digital.Base base) Serializes the current state of this EnhancedRandom and appends it to an Appendable CharSequence (such as a StringBuilder), which may be used byEnhancedRandom.stringDeserialize(String)to load this state at another time.copy()Creates a new EnhancedRandom with identical states to this one, so if the same EnhancedRandom methods are called on this object and its copy (in the same order), the same outputs will be produced.final booleanThe minimum period of a composite of two generators is theEnhancedRandom.lcm(BigInteger, BigInteger)of their getMinimumPeriod() results.longgetSelectedState(int selection) Gets a selected state value from this EnhancedRandom.intGets the number of possible state variables that can be selected withEnhancedRandom.getSelectedState(int)orEnhancedRandom.setSelectedState(int, long).getTag()Gets the tag used to identify this type of EnhancedRandom, as a String.inthashCode()booleanReturns true if this generator mainly operates via itsEnhancedRandom.nextInt()method internally, which means itsEnhancedRandom.nextLong()must generate twointvalues instead of naturally producing onelong.intnext(int bits) Generates the next pseudorandom number with a specific maximum size in bits (not a max number).intnextInt()Returns the next pseudorandom, uniformly distributedintvalue from this random number generator's sequence.longnextLong()Returns the next pseudorandom, uniformly distributedlongvalue from this random number generator's sequence.intOptional; moves the state to its previous value and returns the previous int that would have been produced byEnhancedRandom.nextInt().longOptional; moves the state to its previous value and returns the previous long that would have been produced byEnhancedRandom.nextLong().voidvoidsetRandomA(EnhancedRandom randomA) voidsetRandomB(EnhancedRandom randomB) voidsetSeed(long seed) Sets the seed of this random number generator using a singlelongseed.voidsetSelectedState(int selection, long value) Sets a selected state value to the given longvalue.stringDeserialize(String data, com.github.tommyettinger.digital.Base base) Given a String in the format produced bystringSerialize(Base), and the sameBaseused by the serialization, this will attempt to set this EnhancedRandom object to match the state in the serialized data.stringSerialize(com.github.tommyettinger.digital.Base base) Serializes the current state of this EnhancedRandom to a String that can be used byEnhancedRandom.stringDeserialize(String)to load this state at another time.toString()voidMethods inherited from class com.github.tommyettinger.random.EnhancedRandom
appendSerialized, areEqual, fixGamma, fixGamma, lcm, maxDoubleOf, maxFloatOf, maxIntOf, maxLongOf, minDoubleOf, minFloatOf, minIntOf, minLongOf, nextBoolean, nextBoolean, nextBytes, nextDouble, nextDouble, nextDouble, nextExclusiveDouble, nextExclusiveDouble, nextExclusiveDouble, nextExclusiveDoubleEquidistant, nextExclusiveFloat, nextExclusiveFloat, nextExclusiveFloat, nextExclusiveFloatEquidistant, nextExclusiveSignedDouble, nextExclusiveSignedFloat, nextExponential, nextFloat, nextFloat, nextFloat, nextGaussian, nextGaussian, nextGaussianFloat, nextGaussianFloat, nextInclusiveDouble, nextInclusiveDouble, nextInclusiveDouble, nextInclusiveFloat, nextInclusiveFloat, nextInclusiveFloat, nextInt, nextInt, nextLong, nextLong, nextSign, nextSignedInt, nextSignedInt, nextSignedLong, nextSignedLong, nextTriangular, nextTriangular, nextTriangular, nextTriangular, nextUnsignedInt, probit, processSignedInt32, processUnsignedInt32, randomElement, randomElement, rateGamma, seedFromMath, setState, setState, setState, setState, setState, setState, setState, setState, setState, setState, setState, setWith, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, shuffle, skip, stringDeserialize, stringSerializeMethods inherited from class java.util.Random
doubles, doubles, doubles, doubles, from, ints, ints, ints, ints, longs, longs, longs, longsMethods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, waitMethods inherited from interface java.util.random.RandomGenerator
isDeprecated
-
Field Details
-
randomA
-
randomB
-
-
Constructor Details
-
CompositeWrapper
public CompositeWrapper()Creates a randomly-seeded composite of anOrbitalRandomandXoshiro256StarStarRandom, with a guaranteed period of (2 to the 384) minus (2 to the 128). -
CompositeWrapper
public CompositeWrapper(long seed) Creates a seeded composite of anOrbitalRandomandXoshiro256StarStarRandom, with a guaranteed period of (2 to the 384) minus (2 to the 128). The givenseedis passed to the constructor of each generator.- Parameters:
seed- passed to the constructor of each generator
-
CompositeWrapper
public CompositeWrapper(long stateA, long stateB, long stateC, long stateD, long stateE, long stateF) Creates a seeded composite of anOrbitalRandomandXoshiro256StarStarRandom, with a guaranteed period of (2 to the 384) minus (2 to the 128). The first two states go to the OrbitalRandom constructor, and the last four states go to the Xoshiro256StarStarRandom constructor.- Parameters:
stateA- first state for the OrbitalRandomstateB- second state for the OrbitalRandomstateC- first state for the Xoshiro256StarStarRandomstateD- second state for the Xoshiro256StarStarRandomstateE- third state for the Xoshiro256StarStarRandomstateF- fourth state for the Xoshiro256StarStarRandom
-
CompositeWrapper
Creates a composite of the two given generators, if non-null. Ifais null, this creates a randomly-seeded OrbitalRandom in its place, and ifbis null, this creates a randomly-seeded Xoshiro256StarStarRandom in its place.- Parameters:
a- any EnhancedRandom; null will be replaced with a random OrbitalRandomb- any EnhancedRandom; null will be replaced with a random Xoshiro256StarStarRandom
-
-
Method Details
-
getMinimumPeriod
The minimum period of a composite of two generators is theEnhancedRandom.lcm(BigInteger, BigInteger)of their getMinimumPeriod() results.- Overrides:
getMinimumPeriodin classEnhancedRandom- Returns:
- the least common multiple of
getRandomA().getMinimumPeriod()andgetRandomB().getMinimumPeriod()
-
mainlyGeneratesInt
public boolean mainlyGeneratesInt()Description copied from class:EnhancedRandomReturns true if this generator mainly operates via itsEnhancedRandom.nextInt()method internally, which means itsEnhancedRandom.nextLong()must generate twointvalues instead of naturally producing onelong. This affects how the minimum period is measured forEnhancedRandom.getMinimumPeriod(). Most generators not intentionally targeting Google Web Toolkit mainly operate viaEnhancedRandom.nextLong()here, and return false. A generator that returns true here does not necessarily use 32-bit math; a generator can use 64-bit math internally but only produce 32 bits at a time by truncating its results.- Overrides:
mainlyGeneratesIntin classEnhancedRandom- Returns:
- true if measurements of the period measure calls to
EnhancedRandom.nextInt()instead ofEnhancedRandom.nextLong() - See Also:
-
getStateCount
public int getStateCount()Description copied from class:EnhancedRandomGets the number of possible state variables that can be selected withEnhancedRandom.getSelectedState(int)orEnhancedRandom.setSelectedState(int, long). This defaults to returning 0, making no state variable available for reading or writing. An implementation that has only onelongstate, likeDistinctRandomgenerator, should return1. A generator that permits setting two differentlongvalues, likeLaserRandom, should return2. Much larger values are possible for types like the Mersenne Twister or some CMWC generators.- Overrides:
getStateCountin classEnhancedRandom- Returns:
- the non-negative number of selections possible for state variables
-
getSelectedState
public long getSelectedState(int selection) Description copied from class:EnhancedRandomGets a selected state value from this EnhancedRandom. The number of possible selections is up to the implementing class, and is accessible viaEnhancedRandom.getStateCount(), but negative values forselectionare typically not tolerated. This should return the exact value of the selected state, assuming it is implemented. The default implementation throws an UnsupportedOperationException, and implementors only have to allow reading the state if they choose to implement this differently. If this method is intended to be used,EnhancedRandom.getStateCount()must also be implemented.- Overrides:
getSelectedStatein classEnhancedRandom- Parameters:
selection- used to select which state variable to get; generally non-negative- Returns:
- the exact value of the selected state
-
setSelectedState
public void setSelectedState(int selection, long value) Description copied from class:EnhancedRandomSets a selected state value to the given longvalue. The number of possible selections is up to the implementing class, but negative values forselectionare typically not tolerated. Implementors are permitted to changevalueif it is not valid, but they should not alter it if it is valid. The public implementation callsEnhancedRandom.setSeed(long)withvalue, which doesn't need changing if the generator has one state that is set verbatim by setSeed(). Otherwise, this method should be implemented whenEnhancedRandom.getSelectedState(int)is and the state is allowed to be set by users. Having accurate ways to get and set the full state of a random number generator makes it much easier to serialize and deserialize that class.- Overrides:
setSelectedStatein classEnhancedRandom- Parameters:
selection- used to select which state variable to set; generally non-negativevalue- the exact value to use for the selected state, if valid
-
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.
-
setSeed
public void setSeed(long seed) Description copied from class:EnhancedRandomSets the seed of this random number generator using a singlelongseed. This should behave exactly the same as if a new object of this type was created with the constructor that takes a singlelongvalue. This does not necessarily assign the state variable(s) of the implementation with the exact contents of seed, soEnhancedRandom.getSelectedState(int)should not be expected to returnseedafter this, though it may. If this implementation has more than onelongof state, then the expectation is that none of those state variables will be exactly equal toseed(almost all the time).- Specified by:
setSeedin classEnhancedRandom- Parameters:
seed- the initial seed
-
nextLong
public long nextLong()Description copied from class:EnhancedRandomReturns the next pseudorandom, uniformly distributedlongvalue from this random number generator's sequence. The general contract ofnextLongis that onelongvalue is pseudorandomly generated and returned.
The only methods that need to be implemented by this interface are this andEnhancedRandom.copy(), though other methods can be implemented as appropriate for generators that, for instance, natively produce ints rather than longs.- Specified by:
nextLongin interfaceRandomGenerator- Specified by:
nextLongin classEnhancedRandom- Returns:
- the next pseudorandom, uniformly distributed
longvalue from this random number generator's sequence
-
next
public int next(int bits) Description copied from class:EnhancedRandomGenerates 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 useEnhancedRandom.nextInt(int)instead. For some specific cases, this method is more efficient and less biased thanEnhancedRandom.nextInt(int). Forbitsvalues between 1 and 30, this should be similar in effect tonextInt(1 << bits); though it won't typically produce the same values, they will have the correct range. Ifbitsis 31, this can return any non-negativeint; note thatnextInt(1 << 31)won't behave this way because1 << 31is negative. Ifbitsis 32 (or 0), this can return anyint.The general contract of
nextis that it returns anintvalue and if the argumentbitsis between1and32(inclusive), then that many low-order bits of the returned value will be (approximately) independently chosen bit values, each of which is (approximately) equally likely to be0or1.Note that you can give this values for
bitsthat are outside its expected range of 1 to 32, but the value used, as long as bits is positive, will effectively bebits % 32. As stated before, a value of 0 for bits is the same as a value of 32.- 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
-
nextInt
public int nextInt()Description copied from class:EnhancedRandomReturns 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
-
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()
-
previousInt
public int previousInt()Description copied from class:EnhancedRandomOptional; moves the state to its previous value and returns the previous int that would have been produced byEnhancedRandom.nextInt(). This can be equivalent to callingEnhancedRandom.previousLong()and casting to int, but not always; generators that natively generateintresults typically move the state once in nextInt() and twice in nextLong(), and should move the state back once here.
IfEnhancedRandom.nextInt()is implemented using a call toEnhancedRandom.nextLong(), the implementation in this class is almost always sufficient and correct. If nextInt() changes state differently from nextLong(), then this should be implemented, if feasible, andEnhancedRandom.previousLong()can be implemented using this method. If you know how to implement the reverse of a particular random number generator, it is recommended you do so here, rather than rely on skip(). This isn't always easy, but should always be possible for any decent PRNG (some historical PRNGs, such as the Middle-Square PRNG, cannot be reversed at all). If a generator cannot be reversed because multiple initial states can transition to the same subsequent state, it is known to have statistical problems that are not necessarily present in a generator that matches one initial state to one subsequent state.
The public implementation callsEnhancedRandom.previousLong()and casts it to int, and if previousLong() and skip() have not been implemented differently, then it will throw an UnsupportedOperationException.- Overrides:
previousIntin classEnhancedRandom- Returns:
- the previous number this would have produced with
EnhancedRandom.nextInt()
-
copy
Description copied from class:EnhancedRandomCreates a new EnhancedRandom with identical states to this one, so if the same EnhancedRandom methods are called on this object and its copy (in the same order), the same outputs will be produced. This is not guaranteed to copy the inherited state of any parent class, so if you call methods that are only implemented by a superclass (likeRandom) and not this one, the results may differ.- Specified by:
copyin classEnhancedRandom- Returns:
- a deep copy of this EnhancedRandom.
-
getRandomA
-
setRandomA
-
getRandomB
-
setRandomB
-
equals
-
hashCode
public int hashCode() -
toString
-
stringSerialize
Serializes the current state of this EnhancedRandom to a String that can be used byEnhancedRandom.stringDeserialize(String)to load this state at another time.- Overrides:
stringSerializein classEnhancedRandom- Parameters:
base- which Base to use, from the "digital" library, such asBase.BASE10- Returns:
- a String storing all data from the EnhancedRandom part of this generator
-
appendSerialized
public <T extends CharSequence & Appendable> T appendSerialized(T sb, com.github.tommyettinger.digital.Base base) Description copied from class:EnhancedRandomSerializes the current state of this EnhancedRandom and appends it to an Appendable CharSequence (such as a StringBuilder), which may be used byEnhancedRandom.stringDeserialize(String)to load this state at another time. May use anyBase;Base.BASE10andBase.BASE16are the most intuitive, butBase.SIMPLE64and especiallyBase.BASE90will be more compact.- Overrides:
appendSerializedin classEnhancedRandom- Type Parameters:
T- any type that is both a CharSequence and an Appendable, such as StringBuilder, StringBuffer, or CharBuffer- Parameters:
sb- an Appendable CharSequence that will be modifiedbase- which Base to use, from the "digital" library, such asBase.BASE10- Returns:
sb, for chaining
-
stringDeserialize
Given a String in the format produced bystringSerialize(Base), and the sameBaseused by the serialization, this will attempt to set this EnhancedRandom object to match the state in the serialized data. This only works if this EnhancedRandom is the same implementation that was serialized, and also needs the Bases to be identical. Returns this EnhancedRandom, after possibly changing its state.- Overrides:
stringDeserializein classEnhancedRandom- Parameters:
data- a String probably produced bystringSerialize(Base)base- which Base to use, from the "digital" library, such asBase.BASE10- Returns:
- this, after setting its state
- See Also:
-
readExternal
- Specified by:
readExternalin interfaceExternalizable- Overrides:
readExternalin classEnhancedRandom- Parameters:
in- the stream to read data from in order to restore the object- Throws:
IOException- if there's an input failure
-
writeExternal
- Specified by:
writeExternalin interfaceExternalizable- Overrides:
writeExternalin classEnhancedRandom- Parameters:
out- the stream to write the object to- Throws:
IOException- if there's an output failure
-