Class CompositeWrapper

java.lang.Object
java.util.Random
com.github.tommyettinger.random.EnhancedRandom
com.github.tommyettinger.random.CompositeWrapper
All Implemented Interfaces:
Externalizable, Serializable, RandomGenerator

public class CompositeWrapper extends EnhancedRandom
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 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:
  • Field Details

  • Constructor Details

    • CompositeWrapper

      public CompositeWrapper()
      Creates a randomly-seeded composite of an OrbitalRandom and Xoshiro256StarStarRandom, with a guaranteed period of (2 to the 384) minus (2 to the 128).
    • CompositeWrapper

      public CompositeWrapper(long seed)
      Creates a seeded composite of an OrbitalRandom and Xoshiro256StarStarRandom, with a guaranteed period of (2 to the 384) minus (2 to the 128). The given seed is 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 an OrbitalRandom and Xoshiro256StarStarRandom, 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 OrbitalRandom
      stateB - second state for the OrbitalRandom
      stateC - first state for the Xoshiro256StarStarRandom
      stateD - second state for the Xoshiro256StarStarRandom
      stateE - third state for the Xoshiro256StarStarRandom
      stateF - fourth state for the Xoshiro256StarStarRandom
    • CompositeWrapper

      public CompositeWrapper(EnhancedRandom a, EnhancedRandom b)
      Creates a composite of the two given generators, if non-null. If a is null, this creates a randomly-seeded OrbitalRandom in its place, and if b is null, this creates a randomly-seeded Xoshiro256StarStarRandom in its place.
      Parameters:
      a - any EnhancedRandom; null will be replaced with a random OrbitalRandom
      b - any EnhancedRandom; null will be replaced with a random Xoshiro256StarStarRandom
  • Method Details

    • getMinimumPeriod

      public BigInteger getMinimumPeriod()
      The minimum period of a composite of two generators is the EnhancedRandom.lcm(BigInteger, BigInteger) of their getMinimumPeriod() results.
      Overrides:
      getMinimumPeriod in class EnhancedRandom
      Returns:
      the least common multiple of getRandomA().getMinimumPeriod() and getRandomB().getMinimumPeriod()
    • mainlyGeneratesInt

      public boolean mainlyGeneratesInt()
      Description copied from class: EnhancedRandom
      Returns true if this generator mainly operates via its EnhancedRandom.nextInt() method internally, which means its EnhancedRandom.nextLong() must generate two int values instead of naturally producing one long. This affects how the minimum period is measured for EnhancedRandom.getMinimumPeriod(). Most generators not intentionally targeting Google Web Toolkit mainly operate via EnhancedRandom.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:
      mainlyGeneratesInt in class EnhancedRandom
      Returns:
      true if measurements of the period measure calls to EnhancedRandom.nextInt() instead of EnhancedRandom.nextLong()
      See Also:
    • getStateCount

      public int getStateCount()
      Description copied from class: EnhancedRandom
      Gets the number of possible state variables that can be selected with EnhancedRandom.getSelectedState(int) or EnhancedRandom.setSelectedState(int, long). This defaults to returning 0, making no state variable available for reading or writing. An implementation that has only one long state, like DistinctRandom generator, should return 1. A generator that permits setting two different long values, like LaserRandom, should return 2. Much larger values are possible for types like the Mersenne Twister or some CMWC generators.
      Overrides:
      getStateCount in class EnhancedRandom
      Returns:
      the non-negative number of selections possible for state variables
    • getSelectedState

      public long getSelectedState(int selection)
      Description copied from class: EnhancedRandom
      Gets a selected state value from this EnhancedRandom. The number of possible selections is up to the implementing class, and is accessible via EnhancedRandom.getStateCount(), but negative values for selection are 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:
      getSelectedState in class EnhancedRandom
      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: EnhancedRandom
      Sets a selected state value to the given long value. The number of possible selections is up to the implementing class, but negative values for selection are typically not tolerated. Implementors are permitted to change value if it is not valid, but they should not alter it if it is valid. The public implementation calls EnhancedRandom.setSeed(long) with value, which doesn't need changing if the generator has one state that is set verbatim by setSeed(). Otherwise, this method should be implemented when EnhancedRandom.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:
      setSelectedState in class EnhancedRandom
      Parameters:
      selection - used to select which state variable to set; generally non-negative
      value - the exact value to use for the selected state, if valid
    • getTag

      public String 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 class EnhancedRandom
      Returns:
      a unique String identifier for this type of EnhancedRandom; usually 4 chars long.
    • setSeed

      public void setSeed(long seed)
      Description copied from class: EnhancedRandom
      Sets the seed of this random number generator using a single long seed. This should behave exactly the same as if a new object of this type was created with the constructor that takes a single long value. This does not necessarily assign the state variable(s) of the implementation with the exact contents of seed, so EnhancedRandom.getSelectedState(int) should not be expected to return seed after this, though it may. If this implementation has more than one long of state, then the expectation is that none of those state variables will be exactly equal to seed (almost all the time).
      Specified by:
      setSeed in class EnhancedRandom
      Parameters:
      seed - the initial seed
    • nextLong

      public long nextLong()
      Description copied from class: EnhancedRandom
      Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence. The general contract of nextLong is that one long value is pseudorandomly generated and returned.
      The only methods that need to be implemented by this interface are this and EnhancedRandom.copy(), though other methods can be implemented as appropriate for generators that, for instance, natively produce ints rather than longs.
      Specified by:
      nextLong in interface RandomGenerator
      Specified by:
      nextLong in class EnhancedRandom
      Returns:
      the next pseudorandom, uniformly distributed long value from this random number generator's sequence
    • next

      public int next(int bits)
      Description copied from class: EnhancedRandom
      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 use EnhancedRandom.nextInt(int) instead. For some specific cases, this method is more efficient and less biased than EnhancedRandom.nextInt(int). For bits values between 1 and 30, this should be similar in effect to nextInt(1 << bits); though it won't typically produce the same values, they will have the correct range. If bits is 31, this can return any non-negative int; note that nextInt(1 << 31) won't behave this way because 1 << 31 is negative. If bits is 32 (or 0), this can return any int.

      The general contract of next is that it returns an int value and if the argument bits is between 1 and 32 (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 be 0 or 1.

      Note that you can give this values for bits that are outside its expected range of 1 to 32, but the value used, as long as bits is positive, will effectively be bits % 32. As stated before, a value of 0 for bits is the same as a value of 32.

      Overrides:
      next in class EnhancedRandom
      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: EnhancedRandom
      Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. The general contract of nextInt is that one int value is pseudorandomly generated and returned. All 232 possible int values are produced with (approximately) equal probability.
      Specified by:
      nextInt in interface RandomGenerator
      Overrides:
      nextInt in class EnhancedRandom
      Returns:
      the next pseudorandom, uniformly distributed int value from this random number generator's sequence
    • 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 by EnhancedRandom.nextLong(). This can be equivalent to calling EnhancedRandom.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 generate int results typically produce long 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 by EnhancedRandom.previousInt(), should be reversed. Generators that natively produce long values usually don't need to implement EnhancedRandom.previousInt(), but those that produce int 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 calls EnhancedRandom.skip(long) with -1L, and if skip() has not been implemented differently, then it will throw an UnsupportedOperationException.
      Overrides:
      previousLong in class EnhancedRandom
      Returns:
      the previous number this would have produced with EnhancedRandom.nextLong()
    • previousInt

      public int previousInt()
      Description copied from class: EnhancedRandom
      Optional; moves the state to its previous value and returns the previous int that would have been produced by EnhancedRandom.nextInt(). This can be equivalent to calling EnhancedRandom.previousLong() and casting to int, but not always; generators that natively generate int results typically move the state once in nextInt() and twice in nextLong(), and should move the state back once here.
      If EnhancedRandom.nextInt() is implemented using a call to EnhancedRandom.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, and EnhancedRandom.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 calls EnhancedRandom.previousLong() and casts it to int, and if previousLong() and skip() have not been implemented differently, then it will throw an UnsupportedOperationException.
      Overrides:
      previousInt in class EnhancedRandom
      Returns:
      the previous number this would have produced with EnhancedRandom.nextInt()
    • copy

      public CompositeWrapper copy()
      Description copied from class: EnhancedRandom
      Creates a new EnhancedRandom with identical states to this one, so if the same EnhancedRandom methods are called on this object and its copy (in the same order), the same outputs will be produced. This is not guaranteed to copy the inherited state of any parent class, so if you call methods that are only implemented by a superclass (like Random) and not this one, the results may differ.
      Specified by:
      copy in class EnhancedRandom
      Returns:
      a deep copy of this EnhancedRandom.
    • getRandomA

      public EnhancedRandom getRandomA()
    • setRandomA

      public void setRandomA(EnhancedRandom randomA)
    • getRandomB

      public EnhancedRandom getRandomB()
    • setRandomB

      public void setRandomB(EnhancedRandom randomB)
    • equals

      public final boolean equals(Object o)
      Overrides:
      equals in class Object
    • hashCode

      public int hashCode()
      Overrides:
      hashCode in class Object
    • toString

      public String toString()
      Overrides:
      toString in class Object
    • stringSerialize

      public String stringSerialize(com.github.tommyettinger.digital.Base base)
      Serializes the current state of this EnhancedRandom to a String that can be used by EnhancedRandom.stringDeserialize(String) to load this state at another time.
      Overrides:
      stringSerialize in class EnhancedRandom
      Parameters:
      base - which Base to use, from the "digital" library, such as Base.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: EnhancedRandom
      Serializes the current state of this EnhancedRandom and appends it to an Appendable CharSequence (such as a StringBuilder), which may be used by EnhancedRandom.stringDeserialize(String) to load this state at another time. May use any Base; Base.BASE10 and Base.BASE16 are the most intuitive, but Base.SIMPLE64 and especially Base.BASE90 will be more compact.
      Overrides:
      appendSerialized in class EnhancedRandom
      Type Parameters:
      T - any type that is both a CharSequence and an Appendable, such as StringBuilder, StringBuffer, or CharBuffer
      Parameters:
      sb - an Appendable CharSequence that will be modified
      base - which Base to use, from the "digital" library, such as Base.BASE10
      Returns:
      sb, for chaining
    • stringDeserialize

      public CompositeWrapper stringDeserialize(String data, com.github.tommyettinger.digital.Base base)
      Given a String in the format produced by stringSerialize(Base), and the same Base used 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:
      stringDeserialize in class EnhancedRandom
      Parameters:
      data - a String probably produced by stringSerialize(Base)
      base - which Base to use, from the "digital" library, such as Base.BASE10
      Returns:
      this, after setting its state
      See Also:
    • readExternal

      public void readExternal(ObjectInput in) throws IOException
      Needs the classes of getRandomA() and getRandomB() to both be registered with Deserializer.
      Specified by:
      readExternal in interface Externalizable
      Overrides:
      readExternal in class EnhancedRandom
      Parameters:
      in - the stream to read data from in order to restore the object
      Throws:
      IOException - if there's an input failure
    • writeExternal

      public void writeExternal(ObjectOutput out) throws IOException
      Needs the classes of getRandomA() and getRandomB() to both be registered with Deserializer.
      Specified by:
      writeExternal in interface Externalizable
      Overrides:
      writeExternal in class EnhancedRandom
      Parameters:
      out - the stream to write the object to
      Throws:
      IOException - if there's an output failure