Class GoldenQuasiRandom

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

public class GoldenQuasiRandom extends EnhancedRandom
Not actually a pseudo-random number generator, but a quasi-random number generator, this is an extremely simple way to produce random-seeming numbers with a high distance between one number and the next. This has a period of 2 to the 64. It does not pass any tests for randomness. This is simply a counter with a specific large increment: 2 to the 64 divided by the golden ratio.
Useful traits of this generator are that it has exactly one long of state, that all values are permitted for that state, and that you can skip(long) the state forwards or backwards in constant time. It is also extremely fast, though it shouldn't be compared to pseudo-random number generators. It implements nextGaussian() and its overload specially; these methods advance the state differently and don't return quasi-random output (it's much closer to pseudo-random, and is similar to DistinctRandom's approach). The Gaussian methods needed this treatment because anything that requested multiple Gaussian-distributed variables each time it produced one output (such as a Chi or Beta distribution) would have extremely noticeable, severe artifacts. Because there's always a strong separation between subsequent results of EnhancedRandom.nextDouble(), that made the Gaussian doubles have large gaps in their output range, because some combinations were impossible.
This class is an EnhancedRandom from juniper and is also a JDK Random as a result.
This doesn't randomize the seed when given one with setSeed(long), and it doesn't do anything else to randomize the output, so sequential seeds will produce extremely similar sequences. You can randomize sequential seeds using something like Hasher.randomize3(long), if you want random starting points.
This implements all methods from EnhancedRandom, including the optional skip(long) and previousLong() methods.
See Also:
  • Field Details

    • state

      public long state
      The only long state variable; can be any long.
  • Constructor Details

    • GoldenQuasiRandom

      public GoldenQuasiRandom()
      Creates a new GoldenQuasiRandom with a random state.
    • GoldenQuasiRandom

      public GoldenQuasiRandom(long state)
      Creates a new GoldenQuasiRandom with the given state; all long values are permitted.
      Parameters:
      state - any long value
  • Method Details

    • 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.
    • getStateCount

      public int getStateCount()
      This has one long state.
      Overrides:
      getStateCount in class EnhancedRandom
      Returns:
      1 (one)
    • getSelectedState

      public long getSelectedState(int selection)
      Gets the only state, which can be any long value.
      Overrides:
      getSelectedState in class EnhancedRandom
      Parameters:
      selection - ignored; this always returns the same, only state
      Returns:
      the only state's exact value
    • setSelectedState

      public void setSelectedState(int selection, long value)
      Sets the only state, which can be given any long value. The selection can be anything and is ignored.
      Overrides:
      setSelectedState in class EnhancedRandom
      Parameters:
      selection - ignored; this always sets the same, only state
      value - the exact value to use for the state; all longs are valid
    • setSeed

      public void setSeed(long seed)
      Sets the only state, which can be given any long value; this seed value will not be altered. Equivalent to setSelectedState(int, long) with any selection and seed passed as the value.
      Specified by:
      setSeed in class EnhancedRandom
      Parameters:
      seed - the exact value to use for the state; all longs are valid
    • getState

      public long getState()
      Gets the current state; it's already public, but I guess this could still be useful. The state can be any long.
      Returns:
      the current state, as a long
    • setState

      public void setState(long state)
      Sets each state variable to the given state. This implementation simply sets the one state variable to state.
      Overrides:
      setState in class EnhancedRandom
      Parameters:
      state - the long value to use for the state variable
    • 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
    • skip

      public long skip(long advance)
      Skips the state forward or backwards by the given advance, then returns the result of nextLong() at the same point in the sequence. If advance is 1, this is equivalent to nextLong(). If advance is 0, this returns the same long as the previous call to the generator (if it called nextLong()), and doesn't change the state. If advance is -1, this moves the state backwards and produces the long before the last one generated by nextLong(). More positive numbers move the state further ahead, and more negative numbers move the state further behind; all of these take constant time.
      Overrides:
      skip in class EnhancedRandom
      Parameters:
      advance - how many steps to advance the state before generating a long
      Returns:
      a random long by the same algorithm as nextLong(), using the appropriately-advanced state
    • 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()
    • 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
    • nextInt

      public int nextInt(int bound)
      Description copied from class: EnhancedRandom
      Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All bound possible int values are produced with (approximately) equal probability.
      This method clamps bound to be at least 0; it never returns a negative int.
      It should be mentioned that the technique this uses has some bias, depending on bound, 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 interface RandomGenerator
      Overrides:
      nextInt in class EnhancedRandom
      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) and bound (exclusive) from this random number generator's sequence
    • nextSignedInt

      public int nextSignedInt(int outerBound)
      Description copied from class: EnhancedRandom
      Returns a pseudorandom, uniformly distributed int value between an inner bound of 0 (inclusive) and the specified outerBound (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 than EnhancedRandom.nextInt(int).
      Overrides:
      nextSignedInt in class EnhancedRandom
      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:
    • nextExclusiveDouble

      public double nextExclusiveDouble()
      Description copied from class: EnhancedRandom
      Gets a random double between 0.0 and 1.0, exclusive at both ends; this method is also more uniform than EnhancedRandom.nextDouble() if you use the bit-patterns of the returned doubles. This is a simplified version of this algorithm by Allen Downey. This can return double values between 2.710505431213761E-20 and 0.9999999999999999, or 0x1.0p-65 and 0x1.fffffffffffffp-1 in hex notation. It cannot return 0 or 1. Some cases can prefer EnhancedRandom.nextExclusiveDoubleEquidistant(), which is implemented more traditionally but may have slower performance. This method can also return doubles that are extremely close to 0, but can't return doubles that are as close to 1, due to how floating-point numbers work. However, nextExclusiveDoubleEquidistant() can return only a minimum value that is as distant from 0 as its maximum value is distant from 1.
      To compare, nextDouble() and nextExclusiveDoubleEquidistant() are less likely to produce a "1" bit for their lowest 5 bits of mantissa/significand (the least significant bits numerically, but potentially important for some uses), with the least significant bit produced half as often as the most significant bit in the mantissa. As for this method, it has approximately the same likelihood of producing a "1" bit for any position in the mantissa.
      The implementation may have different performance characteristics than EnhancedRandom.nextDouble(), because this doesn't perform any floating-point multiplication or division, and instead assembles bits obtained by one call to EnhancedRandom.nextLong(). This uses BitConversion.longBitsToDouble(long) and BitConversion.countTrailingZeros(long), both of which typically have optimized intrinsics on HotSpot, and this is branchless and loopless, unlike the original algorithm by Allen Downey. When compared with EnhancedRandom.nextExclusiveDoubleEquidistant(), this method performs better on at least HotSpot JVMs. On GraalVM 17, this is over twice as fast as nextExclusiveDoubleEquidistant().
      Overrides:
      nextExclusiveDouble in class EnhancedRandom
      Returns:
      a random uniform double between 2.710505431213761E-20 and 0.9999999999999999 (both inclusive)
    • nextExclusiveSignedDouble

      public double nextExclusiveSignedDouble()
      Description copied from class: EnhancedRandom
      Gets a random double that may be positive or negative, but cannot be 0, and always has a magnitude less than 1.
      This is a modified version of this algorithm by Allen Downey. This version can return double values between -0.9999999999999999 and -5.421010862427522E-20, as well as between 2.710505431213761E-20 and 0.9999999999999999, or -0x1.fffffffffffffp-1 to -0x1.0p-64 as well as between 0x1.0p-65 and 0x1.fffffffffffffp-1 in hex notation. It cannot return -1, 0 or 1. It has much more uniform bit distribution across its mantissa/significand bits than Random.nextDouble(), especially when the result of nextDouble() is expanded to the -1.0 to 1.0 range (such as with 2.0 * (nextDouble() - 0.5)). Where the given example code is unable to produce a "1" bit for its lowest bit of mantissa (the least significant bits numerically, but potentially important for some uses), this has approximately the same likelihood of producing a "1" bit for any positions in the mantissa, and also equal odds for the sign bit.
      Overrides:
      nextExclusiveSignedDouble in class EnhancedRandom
      Returns:
      a random uniform double between -1 and 1 with a tiny hole around 0 (all exclusive)
    • nextExclusiveFloat

      public float nextExclusiveFloat()
      Description copied from class: EnhancedRandom
      Gets a random float between 0.0 and 1.0, exclusive at both ends. This method is also more uniform than EnhancedRandom.nextFloat() if you use the bit-patterns of the returned floats. This is a simplified version of this algorithm by Allen Downey. This version can return float values between 2.7105054E-20 to 0.99999994, or 0x1.0p-65 to 0x1.fffffep-1 in hex notation. It cannot return 0 or 1. To compare, nextFloat() is less likely to produce a "1" bit for its lowest 5 bits of mantissa/significand (the least significant bits numerically, but potentially important for some uses), with the least significant bit produced half as often as the most significant bit in the mantissa. As for this method, it has approximately the same likelihood of producing a "1" bit for any position in the mantissa.
      The implementation may have different performance characteristics than EnhancedRandom.nextFloat(), because this doesn't perform any floating-point multiplication or division, and instead assembles bits obtained by one call to EnhancedRandom.nextLong(). This uses BitConversion.intBitsToFloat(int) and BitConversion.countLeadingZeros(long), both of which typically have optimized intrinsics on HotSpot, and this is branchless and loopless, unlike the original algorithm by Allen Downey. When compared with EnhancedRandom.nextExclusiveFloatEquidistant(), this method performs better on at least HotSpot JVMs. On GraalVM 17, this is over twice as fast as nextExclusiveFloatEquidistant().
      Overrides:
      nextExclusiveFloat in class EnhancedRandom
      Returns:
      a random uniform float between 0 and 1 (both exclusive)
    • nextExclusiveSignedFloat

      public float nextExclusiveSignedFloat()
      Description copied from class: EnhancedRandom
      Gets a random float that may be positive or negative, but cannot be 0, and always has a magnitude less than 1.
      This is a modified version of this algorithm by Allen Downey. This version can return double values between -0.99999994 and -1.1641532E-10, as well as between 2.7105054E-20 and 0.99999994, or -0x1.fffffep-1 to -0x1.0p-33 as well as between 0x1.0p-65 and 0x1.fffffep-1 in hex notation. It cannot return -1, 0 or 1. It has much more uniform bit distribution across its mantissa/significand bits than Random.nextDouble(), especially when the result of nextDouble() is expanded to the -1.0 to 1.0 range (such as with 2.0 * (nextDouble() - 0.5)). Where the given example code is unable to produce a "1" bit for its lowest bit of mantissa (the least significant bits numerically, but potentially important for some uses), this has approximately the same likelihood of producing a "1" bit for any positions in the mantissa, and also equal odds for the sign bit.
      Overrides:
      nextExclusiveSignedFloat in class EnhancedRandom
      Returns:
      a random uniform double between -1 and 1 with a tiny hole around 0 (all exclusive)
    • nextGaussian

      public double nextGaussian()
      Description copied from class: EnhancedRandom
      Returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.

      The general contract of nextGaussian is that one double value, chosen from (approximately) the usual normal distribution with mean 0.0 and standard deviation 1.0, is pseudorandomly generated and returned.

      This does not use a rough approximation, which is a departure from earlier versions; instead, it uses the Ziggurat method, which produces high-quality variables very quickly. Like earlier versions that used probit() or a bit-counting approximation, this requests exactly one long from the generator's sequence (using EnhancedRandom.nextLong()). This makes it different from code like java.util.Random's nextGaussian() method, which can (rarely) fetch a higher number of random doubles.

      The implementation here was ported from code by Olaf Berstein, based on a paper by Jorgen A. Doornik and some steps from a paper by George Marsaglia. Ziggurat has more information, for the curious.

      Specified by:
      nextGaussian in interface RandomGenerator
      Overrides:
      nextGaussian in class EnhancedRandom
      Returns:
      the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence
    • copy

      public GoldenQuasiRandom 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.
    • equals

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

      public String toString()
      Overrides:
      toString in class Object